▲ | tialaramex 5 days ago | ||||||||||||||||
The compiler isn't ignoring your new types, as you'll see if you try to pass a OneVar when the function takes a Vec but yes, Rust really likes new types whose representation is identical yet their type is different. My favourite as a Unix person is Option<OwnedFd>. In a way Option<OwnedFd> is the same as the classic C int file descriptor. It has the exact same representation, 32 bits of aligned integer. But Rust's type system means we know None isn't a file descriptor, whereas it's too easy for the C programmer to forget that -1 isn't a valid file descriptor. Likewise the Rust programmer can't mistakenly do arithmetic on file descriptors, if we intend to count up some file descriptors but instead sum them in C that compiles and isn't what you wanted, in Rust it won't compile. | |||||||||||||||||
▲ | Ygg2 5 days ago | parent [-] | ||||||||||||||||
> The compiler isn't ignoring your new types True, I didn't meant to imply you can just ignore types; I meant to say that the equivalent operations on a naked vs wrapped value return equivalent assembly. It's one of those zero cost abstraction. You can writ your newtype wrapper and it will be just as if you wrote implementations by hand. > My favourite as a Unix person is Option<OwnedFd>. Yeah, but that's a bit different. Compiler won't treat any Option<T> that way out of the box. You need a NonZero type or nightly feature to get that[1]. That relies on compiler "knowing" there are some values that will never be used. [1] https://www.0xatticus.com/posts/understanding_rust_niche/ | |||||||||||||||||
|