Does [bool] save space over [u8]?

If I want to store the representation of a binary number into an array, does it make a difference to use [bool] instead of [u8]? Will each bool take 1 bit instead of 8 bits for u8?

No. bool takes 1 byte.
If you want to save space, use a bitvector.

1 Like

No, bool occupies a full byte, but only 0 and 1 are valid raw values. That means there's a niche such that things like Option<bool> are still only one byte, where None takes an unused value (probably 2).

1 Like

It is impossible to pack a slice of bools into bits, since the slice api states that for each element its address can be taken, and is just a usual pointer, but it's impossible to create pointers to individual bits.

If you want to pack bools into bits, consider using the bitvec or bitflags crates.


Why not check it for yourself using size_of?

use std::mem::size_of;

println!("bools: {}, bytes: {}", size_of::<[bool; 8]>(), size_of::<[u8; 8]>());

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.