Is it worth implementing the Deref trait for newtypes in Rust?
Hi everyone! I recently started learning Rust and came across an interesting code design question. I often create wrappers over existing types to add semantics or restrict functionality. For example, I have a `UserId` type that internally stores a `u64`:
```rust
struct UserId(u64);
```
I want `UserId` to work almost like `u64` (comparable, printable, copyable). I can, of course, manually implement the `Display` or `PartialEq` traits, but that's a lot of code.
However, I stumbled upon an idiom where for such newtypes people implement the `Deref` trait:
```rust
use std::ops::Deref;
impl Deref for UserId {
type Target = u64;
fn deref(&self) -> &u64 {
&self.0
}
}
```
Now I can call `u64` methods directly on `UserId`, and it
No answers yet.
Log in to leave an answer
Blogs