Declare struct with default values?

Is there a create that would let me do something like this?

struct!(Foo, {
  bar:String = "bar".to_string(),
  baz:u32 = 42

and it would generate the struct as well as the Default impl with those values?

Sortof like vec! I guess but for structs...

There's this syntax?

Foo {
    bar: "bar".to_string(),
    baz: 42,

It requires Foo to implement the Default trait.

The problem is that I want to avoid having to write that Default trait impl, since it's all just declared statically - like a top-level configuration object with hardcoded values.

Writing the struct twice feels a bit unnecessary, even if once is for the types and the second is for the values - would be nice to have it all in one place.

Unfortunately a macro is not able to go automatically look up which fields are in the struct, so it's not really possible for it to fill out the remaining fields. You could make a macro for the specific type, with the fields hard-coded.

1 Like

This seems to get pretty close: (hat-tip @leudz)

definitly possible:
It would require some tweaking to add pub.

1 Like

Macros still seem like magic to me... I get what they're doing but the syntax is daunting.


If you publish this into its own crate please mention it here if you happen to remember :wink:

The problem is… writing that macro wasn't a big deal (as I have used them for way too long).
Polishing it into something that can be released as a crate (all the visibility attributes) is another thing and probably a task for proc_macro.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.