Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If you do have the struct implementing `Default`, as suggested from sibling comments, and it's fully public, you can also use the "functional update syntax" (where the `..` is):

    #[derive(Default)]
    struct Config {
        interesting_thing: bool,
        a: i32,
        b: i32,
        c: i32,
    }   
    
    fn main() {
        Config {
            interesting_thing: true,
            ..Config::default()
        };
    }
In addition, the builder pattern is especially useful for larger configuration objects like this.


I think the derive_builder crate is worth a mention here:

https://docs.rs/derive_builder/0.5.0/derive_builder/


The main reason I haven't used derive_builder much is that I'd much rather have a compile-time guarantee that all the field that I want are filled out than have to check for an error at runtime (or worse, just `unwrap/expect` everywhere). I'm not sure there's currently a way around this on stable, but I'd personally prefer writing boilerplate for my types than having to handle errors in places that shouldn't need them.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: