Effective way to create 2 bit numbers?

I really like how Rust lets You do low-level things like decide how many bits your numbers use, But you can only choose between 8, 16, 32, 64, and 128 bit numbers, A variable I am using has only four possible values, so how could I make it the equivalent to a u2?

It is not possible to address less than a byte using Rust. (Just like it is not possible to manipulate less than a byte on basically any modern computer architecture.)

Generally, if you want to semantically express a choice out of a number of possibilities, you should use an enum, which will be checked at compile time to only ever contain one of its specified variants.

6 Likes

If you're willing to write out all the possible bit strings (so definitely not for "all even 64-bit numbers") then you can make those enum variants and get a custom validity invariant through that.

See this hack, for example:

2 Likes

That example is from the core Library, right?