Ah yeah, via deref coercion, which is also called “auto-dereferencing” at times. Not to be confused with “auto-referencing”, which is also a thing[1].
You can do some wild shit with deref coercion. And when I say “wild”, I guess, I’m talking about the most normal thing for Java devs, because well, it’s a lot like inheritance. 😅
Basically, this concept of being able to pass &String into a parameter that takes &stralso applies to the self parameter. Or in other words, methods implemented on str can also be called on String, as if Stringextends str.
And well, obviously you can also make use of that yourself, by writing your own wrapper type. You can even “override” existing methods in a sense by re-defining them in the wrapper type.
I like this rule of thumb and it goes nicely with the “if you have more than 3 arguments to a function, consider making a struct to pass the arguments in” rule of thumb because
You can have the struct use a named lifetime (or several) for the different parameters so it doesn’t own them!
The rule of thumb I always tell people is that they should generally put owned data into struct fields and references into function parameters.
I recently learned you can pass a
&Stringto a&strparameter, so that’s neat.Ah yeah, via deref coercion, which is also called “auto-dereferencing” at times. Not to be confused with “auto-referencing”, which is also a thing[1].
You can do some wild shit with deref coercion. And when I say “wild”, I guess, I’m talking about the most normal thing for Java devs, because well, it’s a lot like inheritance. 😅
Basically, this concept of being able to pass
&Stringinto a parameter that takes&stralso applies to theselfparameter. Or in other words, methods implemented onstrcan also be called onString, as ifString extends str.And well, obviously you can also make use of that yourself, by writing your own wrapper type. You can even “override” existing methods in a sense by re-defining them in the wrapper type.
I had to play around a bit with it myself, so here’s a playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=af65ed396dec88c8406163acaa1f8f8d
https://doc.rust-lang.org/nomicon/dot-operator.html ↩︎
Welp, I posted my hot take that
impl Derefis similar to inheritance as a meme in !rust@lemmy.ml: https://lemmy.ml/post/42514248Now, let’s see how many feathers get ruffled. 🙃
Good rule of thumb. As long as it’s not followed blindly of course.
Structs with lifetimes are often quite convenient. Especially for performance.
I like this rule of thumb and it goes nicely with the “if you have more than 3 arguments to a function, consider making a struct to pass the arguments in” rule of thumb because
You can have the struct use a named lifetime (or several) for the different parameters so it doesn’t own them!
Best of both worlds.