I have already an answer here on how to setup and use an enum if we want bitwise operations.
On the other hand, we can combine enum values in a vector (dynamic array) and use them as they are:
#[derive(Debug)]
enum BITS {
ONE = 0b0001,
TWO = 0b0010,
FOUR = 0b0100,
EIGHT = 0b1000,
}
fn main() {
let flags: Vec<BITS>;
flags = vec![BITS::ONE, BITS::FOUR, BITS::EIGHT];
println!("{flags:?}");
use_flags(flags);
}
fn use_flags(flags:Vec<BITS>){
for flag in flags{
match flag {
BITS::ONE => println!("flag ONE is set"),
BITS::TWO => println!("flag TWO is set"),
BITS::FOUR => println!("flag FOUR is set"),
BITS::EIGHT => println!("flag EIGHT is set")
}
}
}
the thing here is to set default values (with mut) inside our function and use the match
to customize them later down the code.
it is easy to code but the downside of this approach is the memory usage for each flag inside the vector.
in the bit operation approach, bits of enum values should not overlap. the forethought process is essential in that approach. and also unpacking bit fields is not easy, yet storing them in bit fields makes it efficient for memory. so check my other answer too. (https://stackoverflow.com/a/76603396/9512475)