This rust-analyzer style guide recommends accessors like this:
struct Person {
// Invariant: never empty
first_name: String,
middle_name: Option<String>
}
impl Person {
fn first_name(&self) -> &str { self.first_name.as_str() }
fn middle_name(&self) -> Option<&str> { self.middle_name.as_ref() }
}
However, when I use this pattern, the compiler complains about the return value of middle_name():
mismatched types
expected enum `std::option::Option<&str>`
found enum `std::option::Option<&std::string::String>`
It works if I change the return value of the accessor to Option<&String>. But in Rust doesn’t one generally want to use &str and not &String, as in first_name()? How does one do that with optionals? Or is Option<&String> actually the correct pattern and the style guide is out of date?
You can use Option::as_deref to convert an Option<String> into an Option<&str>.
impl Person {
fn first_name(&self) -> &str { self.first_name.as_str() }
fn middle_name(&self) -> Option<&str> { self.middle_name.as_deref() }
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With