4 ms·
I will shamefully admit to using transmute in very sinful ways, such as having enums that are repr(u16) or something like that at multiple numeric ranges such a
by luizfelberti 5y ago
I will shamefully admit to using transmute in very sinful ways, such as having enums that are repr(u16) or something like that at multiple numeric ranges such as:
#[repr(u16)]
enum Foo { A = 0, B }
#[repr(u16)]
enum Bar { A = 3200, B }
struct FooOrBar(u16);
And then proceeding to violate all of the unwritten rules of Rust by wrangling casts across these types like a goddamn wizard
I'm not proud of this...
- lilyball 5y agoThis sounds like a great example of where you might want a union (https://doc.rust-lang.org/1.56.0/reference/items/unions.html https://doc.rust-lang.org/1.56.0/reference/items/unions.html)
- luizfelberti 5y agoOoh I forgot the language had those! I still feel like this trick has it's place though, as an example take a look at where I stole this trick from, by matklad [0] and tell me what you think :) [0] https://github.com/rust-analyzer/rowan/blob/d2c7843858da9d9e378de790bd14487c848f6f2e/examples/s_expressions.rs#L51 https://github.com/rust-analyzer/rowan/blob/d2c7843858da9d9e...
- lilyball 5y agoI think that this code is acceptable as long as you're careful. And I wish Rust had a `#[derive(TryFrom)]` sort of thing for deriving conversions from the declared primitive type to the enum.