top | item 41031487

(no title)

devanl | 1 year ago

In Rust, you can't implicitly omit fields when instantiating a struct, so it would have to be a bit more verbose, explicitly using Rust's analog to the spread syntax.

It would have to look something like:

  f({ hours: 2, seconds: 53, ..Default::default() })

The defaults could come from some value / function with a name shorter than Default::default(), but it would be less clear.

discuss

order

estebank|1 year ago

Adding support for struct default field values would allow for

- leaving some mandatory fields

- reduce the need for the builder pattern

- enable the above to be written as f(S { hours: 2, seconds: 53, .. })

If that feature ever lands, coupled with structural/anonymous structs or struct literal inference, you're getting everything you'd want from named arguments without any of the foot guns.

kibwen|1 year ago

Has anyone ever proposed it? It's such a straightforward feature with such obvious semantics ("default field values are const contexts") and impossible-to-bikeshed syntax (`a: i32 = 42`) that I've been meaning to write up an RFC myself for around, oh, ten years now...