3 ms·
Good idea with unsafe traits. Maybe something like unsafe trait IsZero: Copy { fn is_zero(&self) -> bool; } #[derive(Copy, IsZero)] struct Foo {
by conradludgate 5y ago
Good idea with unsafe traits. Maybe something like
unsafe trait IsZero: Copy {
fn is_zero(&self) -> bool;
}
#[derive(Copy, IsZero)]
struct Foo {
a: u8,
b: u16,
}
which could derive into
unsafe impl IsZero for Foo {
fn is_zero(&self) -> bool {
true
&& self.a.is_zero()
&& self.b.is_zero()
}
}
- conradludgate 5y agoThere needs to be some thought into how it works with Enums too. Rust currently has no built in standard for enum defaults (you have to implement default yourself). It would be nice to somehow mark one of the variants to be represented with the 0 discriminant (Like how Option::None is implemented)
- estebank 5y agoThe RFC for that has been recently accepted[1] and the implementation is already available in nightly[2]. [1]: https://rust-lang.github.io/rfcs/3107-derive-enum-default.html https://rust-lang.github.io/rfcs/3107-derive-enum-default.ht... [2]: https://github.com/rust-lang/rust/pull/86735 https://github.com/rust-lang/rust/pull/86735
- conradludgate 5y agoUnfortunately there's still no guarantee for which variant will be represented by 0
- erk__ 5y agoYou may also have cases where no variant is 0 so this case is probably not as straightforward
- estebank 5y agoThe comment is fair. There have been some talks about being able to allow end users specify niches so that if you could have something like enum E<T> { Empty = 42, Some(NonFortyTwo<T>), } in the same way that the following is of size T today enum E<T> { Empty = 0, Some(NonZero<T>), } but that's not possible today.
- tialaramex 5y agoYes, I can see uses for this. Forty-two is obviously not something you'd actually want, but I can see needing numbers in the range 0-100 and being frustrated that since I need 0 I can't carve out a niche even though I don't mind losing 101 through 255 from a u8 instead of making my type wider. Still the existing tricks get a lot done for relatively little work. I have used Option<NonZeroUsize> to do roughly what I'd use a single integer for in C, but making explicit that zero isn't just zero, but "I dunno, invalid". Would I have done that even if it cost more space? Probably, but it was cool that I didn't even need to consider that, "Zero cost abstraction".
- erk__ 5y agoYeah something like this would be how I would like to see it, the trait is already there and is pretty much that (without the Copy bound though as that is not needed.) Hopefully it will end up public and can be implemented with a derive.