Converting Option<String> to Option<&str> in Rust: how to do it correctly?
Hello everyone! I just started learning Rust and encountered a type conversion problem. I have a function that returns `Option`, but I need to pass its result to another function that expects `Option<&str>`.
Here's a simplified example:
```rust
fn get_name() -> Option {
Some("Alice".to_string())
}
fn print_name(name: Option<&str>) {
match name {
Some(n) => println!("Hello, {}", n),
None => println!("No name provided"),
}
}
fn main() {
let name = get_name();
// How to pass name to print_name?
print_name(name); // Compilation error!
}
```
The compiler gives an error: `expected Option<&str>, found Option`. I understand that `String` and `&str` are different types, but how do I correctly convert `Option` to `Option<&str>`?
No answers yet.
Log in to leave an answer