kmp
kmp

Reputation: 10875

What's the alternative to u32::BITS in a const?

I have a bit of code that does this:

const MY_CRAZY_CONSTANT: u32 = 1 << (u32::BITS - 1); 

I tried to compile it using Rust nightly (2016-03-29) and it fails with the message:

error: no associated item named `BITS` found for type `u32` in the current scope

I see that it was deprecated and I see there was an RFC (Sizeof, alignof, offsetof, typeof #591) talking about adding a sizeof keyword etc, but that is closed: postponed.

I guess the deprecation has come to fruition in the nightly channel in that it has been removed and I know I can do the following, but to do that I would need to remove my const, which I would rather not do.

mem::size_of::<u32>() * 8

So, is it now the case that I must remove my const and re-structure my code or is there some other way to achieve what I had originally?

Upvotes: 5

Views: 261

Answers (1)

Shepmaster
Shepmaster

Reputation: 431679

The general answer is to define your own constant:

const U32_BITS: usize = 32;

for the special case of usize::BITS or isize::BITS, you will need to use conditional compilation.

#[cfg(target_pointer_width = "32")]
const USIZE_BITS: usize = 32;
#[cfg(target_pointer_width = "64")]
const USIZE_BITS: usize = 64;

Upvotes: 3

Related Questions