this post was submitted on 21 Apr 2024
66 points (97.1% liked)
Rust
5966 readers
5 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Thank you very much. I’ll change it. I did run cargo clippy, but it didn’t complained anything anymore before I published the code. 🙂
One question to return value
Option<&String>
:is it better to change to
Option<&str>
or&Option<String>
if the value in the struct is aOption<String>
? The latter sounds more logical to me.@larix @Ephera it's better to return an Option<&str> as a String may DeRef to &str.
For example
self.name.as_deref()
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.@larix
Yes, that makes sense too. Great!
I’ve updated the code as recommended.
@Ephera@lemmy.ml @jcbritobr@mastodon.social
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...