this post was submitted on 29 Jul 2023
12 points (92.9% liked)
Rust
6340 readers
7 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
This is not possible, because Rust still stores a discriminant even when the enum values don't overlap.
As far as I can tell, the only situation where Rust doesn't store a discriminant is when either the
Ok
orErr
variant is zero-sized, and the other variant has a niche. So,Result<(), ErrorEnum>
can be represented as an integer, butResult
can not.You can still use enums, and implement simple conversions like this:
P.S. Sorry that the generics aren't displayed due to Lemmy's bad santiziation.
Discriminant is irrelevant and you're not supposed to fuck with it.
And there is zero reason to use unsafe/transmute for this.
It matters because the conversion between i32 and the Result is only "free" if they have the same layout (which they do not, because of the discriminant). So a more costly conversion method is required.
You are right, because the compiler is able to optimize your code quite well. However, if that optimization were to break at some point (as there is no guarantee that an optimization will continue to work in the future), it would become less efficient.
That seems like strong premature optimisation. Perhaps worth a note, but I'd presume the majority of people the majority of the time wouldn't need to worry about that.
For real. Unless he's converting between results and ints millions of times a second, I think he's going to be just fine using the idiomatic solution. That transmute shit I'd wack lol