What's the idiomatic way to store flags?


#1

Hi. Although it sounds quite obvious, nevertheless, by reading documentation I didn’t understand
the proper way to store flags, sadly.

#define FIRSTFLAG = 0x01
#define SECONDFLAG = 0x02
#define THIRDFLAG = 0x04

Should I use constants, or struct, or enum, or macros to convert above C code into idiomatic Rust code?

Thanks.


#2

In rust, I think the preferred way to handle binary flags is via specialized crates such as bitflags.


#3

What about implementing behaviour using language’s built-in tools?


#4

Letting a crate handle that is Rust’s way of using the language, mostly because it’s easy and straight-forward to add dependencies. bitflags does no magic, but produces regular Rust code. You’re of course free to write individual constants instead.


#5

Is third-party crate preferred even if one writes program for resource constrained environments?
Say, firmware for embedded devices(microwave oven, toster, etc…)?


#6

Depends on what crate brings with itself.

Sometimes you have simple macros in crates, so it is mostly harmless.

Bitflags brings only simple bit manipulation routines, so it should not produce any problems compared to handwritten implementation.


#7

It’s fine to use crates. There are even “no std” crates for microcontrollers that are too small to use Rust standard library.