3 ms·
In Rust I find myself gaining a good bit of type safety without losing ergonomics by wrapping types in a newtype then implementing Deref for them. At first it m
by nixpulvis 1y ago
In Rust I find myself gaining a good bit of type safety without losing ergonomics by wrapping types in a newtype then implementing Deref for them. At first it might seem like a waste, but it prevents accidentally passing the wrong type of thing to a function (e.g. a user UUID as a post UUID).
- weinzierl 1y agoThis and for the use case from the article we will hopefully gain pattern types in Rust soon. They do not solve every problem that constructive data modeling does but in my opinion a large portion of what actually occurs in everyday programs. Since they are zero-cost I'd say their cost-benefit ratio is pretty good. Ada and Pascal also had handled the "encode the range in the type" nicely for decades.
- chiffaa 1y agoI want to point out that, technically, using Deref for this is an anti-pattern, as Deref is intended exclusively for smart pointers. Nothing really wrong with doing this outside of some loss in opacity (and unexpected behaviour if you're writing a library), but it's worth pointing out
- OptionOfT 1y agoNote that that language has changed: https://github.com/rust-lang/rust/commit/58645e06d9121ae37654b812d14041d0229d49c3#diff-6272bd172cf4be3f42a8e384d02cd6c72d8a9e9b7df2b228a72f02d052557162L11 https://github.com/rust-lang/rust/commit/58645e06d9121ae3765...
- nixpulvis 1y agoI don't really see the issue in providing Deref for a wrapper type like this. Could you elaborate? I'm not trying to gain full encapsulation, just trying to make sure I'm passing the right kind of wrapper, then using it transparently.