What's the idiomatic way to store flags?

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.

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

2 Likes

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

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.

2 Likes

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

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.

3 Likes

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

1 Like