Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best borrowing accessor pattern for Optional<String>?

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?

like image 446
theory Avatar asked Oct 20 '25 02:10

theory


1 Answers

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

like image 191
John Kugelman Avatar answered Oct 22 '25 05:10

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!