Elektrine lite

โ† Feed

@Ephera@lemmy.ml

Post #2584661

2026-02-01 04:00 UTC

Ah yeah, via [deref coercion](https://doc.rust-lang.org/book/ch15-02-deref.html#using-deref-coercion-in-functions-and-methods), 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 `&str` *also* applies to the `self` parameter. Or in other words, methods implemented on `str` can also be called on `String`, as if `String 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 [^1]: https://doc.rust-lang.org/nomicon/dot-operator.html

Replies (1)

  • @Ephera@lemmy.ml 2026-02-01 07:12

    Welp, I posted my hot take that `impl Deref` is similar to inheritance as a meme in !rust@lemmy.ml: https://lemmy.ml/post/42514248 Now, let's see how many feathers get ruffled. ๐Ÿ™ƒ

    Open ##2584662