I believe, it's also not a thing to return &String (nor to store it in a struct). I don't have as solid of an explanation for it, it's just not something I see much in Rust code (and in the chapter above, they do use a &str as return value, too).
Maybe someone else can weigh in on that.
The same applies for:
&[] rather than &Vec
&Path rather than &PathBuf
&OsStr rather than &OsString
I would also recommend using Clippy. I think, you can just run cargo clippy and it'll work.
It's a linter and will tell you lots of code style issues (like using &String as a parameter).
If you've never run it, it might spit out a lot of warnings at first, but working through them can teach you quite some things.
Hmm, interesting. The documentation tells me, it creates a new Option value, and allocating memory every time someone just wants to look at a value could be pretty bad.
But I guess, an Option of a reference never needs to allocate memory, because it'll either be a pointer to a value (Some) or a pointer to null (None). Right?
Well, that explains why it's technically possible.
As for why Option<&str> is preferrable then:
It hides away your internals. Your caller should only care whether they can get the value or not (Some vs. None), not what the precise reason is. That reason or your internal structure might change.
Well, that explains why it's technically possible.
As for why Option<&str> is preferrable then:
It hides away your internals. Your caller should only care whether they can get the value or not
(Some vs. None), not what the precise reason is. That reason or your internal structure might change.
Hmm, not quite sure why Clippy didn't say anything then. I think, it was a Option<&String> which I had seen as a parameter type. Maybe it doesn't complain when it's wrapped in an Option...