Struct with elements not set

I'm trying to automatically generate structs from a definition file I have. An example might look something like this.

#[derive(Debug)]
struct TestStruct {
    name: String,
    email: String,
    employee: bool,
    age: Option<u16>,
    height: Option<u16>
} 

So I would like to be able to create the struct but I might not know the values I want to put in at this point.
Is there a way to Default the Options to None and automatically default employee to true or false?
Is there a way to set "name" as some sort of blank value and I will be passing this to serde_json if it's not set by that point I get a compiler error?

If you derive the Default trait:

#[derive(Debug, Default)]
struct TestStruct { ... }

then you can call TestStruct::default() to create a TestStruct with all the strings set to "", the bool field set to false, and the Option fields set to None.

If you want to choose different default values, you can impl Default for TestStruct explicitly instead of deriving it.

However, this is still a valid value so it won't cause an error when serializing it. If you want to prevent use of TestStruct until all the fields are initialized, you might want to implement the "builder" pattern, perhaps using a crate like derive_builder.

2 Likes

If you need to distinguish between "default value" and "was never set", or more strictly guarantee that you checked for validity sometime after the initial struct creation, you could use a separate type while populating, which must be converted once populated (to get you the compiler-backed type safety).