Conditionally include field in my struct based on arch

I would like to know if it's possibile to include a specific field based on the current arch. I found docs about doing that with functions but now with fields.

Something like:

struct MyStruct {
  #[cfg(target_arch = "arm")]
  pub my_field: u8,
  pub other_field: u8,

}

to create with something like that:

let struct = if cfg!(target_arch = "arm") {
   MyStruct { my_field:10, other_field:20 }
} else {
  MyStruct {other_field:20 }
}

You could achieve your desire more easily than you wrote:

#[derive(Debug)]
pub struct Struct{
    #[cfg(feature="fine")]
    pub fine:u8,
    pub always:u8
}
impl Struct {
    pub fn new()->Self{
        Self{
            #[cfg(feature="fine")]
            fine:0,
            always:0
        }
    }
}
fn main(){
    let a=Struct::new();
    println!("{a:?}")
}

I uses #[cfg(feature="fine")] for test propose, you could use

rustc --edition 2021 test.rs  -o test && ./test

to compile the program without features, and

rustc --edition 2021 test.rs --cfg feature="fine" -o test  && ./test

to compile the program with feature fine.


Please do not use

let struct = if cfg!(target_arch = "arm") {
   MyStruct { my_field:10, other_field:20 }
} else {
  MyStruct {other_field:20 }
}

in any part of your code, since you could not tell everyone add a cfg! branch in compile time.

It might be better to write some function like new or new_with, hide the extra optional variable.

2 Likes