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() }
}