Search code examples
rustconditional-compilation

How to make type aliases based on compile flags in Rust?


I want to alias the type uint to u32 by default, but a flag can be set during compilation to change it to usize. The code should be something like this:

#[cfg(uint='u32') || default]
type uint = u32;
#[cfg(uint='usize')]
type uint = u64;

And when I compile, I can use cargo build --uint=usize. What should I do to make this work?


Solution

  • The feature you want doesn't exist. There are a few ways to fake it.

    First, you can use features:

    #[cfg(all(feature="uint-is-u16", not(any(feature="uint-is-u32", feature="uint-is-u64"))))]
    type uint = u16;
    #[cfg(not(any(feature="uint-is-u16", feature="uint-is-u64")))]
    type uint = u32;
    #[cfg(all(feature="uint-is-u64", not(any(feature="uint-is-u16"))))]
    type uint = u64;
    

    These are specified using cargo build --features=uint-is-u64. Note that features are strictly additive, and you cannot make "exclusive" features: i.e. you can't make it impossible to specify both u64 and u32. As such, you need to structure the code such that it works even if multiple features are enabled.

    Alternately, you could put the setting in a configuration file somewhere, and write a build script that emits the type alias as code (see the code generation example).