How rust struct optionals simplify code

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Test{
  pub a: Option<String>,
  pub b: Option<String>,
  pub c: Option<String>,
  pub d: Option<String>,
  pub e: Option<String>,
}

new a struct

let s = Test {
  a = Some(String::from("have a vlue"))
 b = None,
 c = None,
 d = None,
 e = None,
}

Is there a simplified writing method ?

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
//                                             ^^^^^^^
pub struct Test {
    pub a: Option<String>,
    pub b: Option<String>,
    pub c: Option<String>,
    pub d: Option<String>,
    pub e: Option<String>,
}

fn main() {
    let _s = Test {
        a: Some(String::from("have a vlue")),
        ..Default::default()
//      ^^^^^^^^^^^^^^^^^^^^
    };
}

Playground.

See also.

2 Likes

Use FRU, like

    let s = Test {
        c: Some("hello".into()),
        ..Default::default()
    };

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9f783e3c86ba8f6573eda2ac836b00cb

EDIT: Doh, @quinedot beat me :upside_down_face:

3 Likes

thanks thanks