Thanks @spacekookie!
I know is a long thread so it is a good time to summarize what the RFC I'll be writing will propose, particularly because it is removed from what I originally wrote:
-
Language support for default values on
struct
s throughconst
expressions:struct Car { wheel_count: usize = 4; }
-
Language support for partially defaulted
struct
s:struct Person { name: String, age: i128 = 0; }
-
Teach
#[derive(Default)]
to use the default values#[derive(Default)] struct Pet { name: Option<String>, // impl Default for Pet will use Default::default() for name age: i128 = 0; // impl Default for Pet will use the literal 0 for age }
-
Expand the "spread"
..
operator to make the RHS expression optional, if it is not present it will use the defaultconst
expressions set in thestruct
definition:let person = Person { name: "Jane Austen".to_string(), .. }; let person = Person { name: "Margaret Atwood".to_string(), ..Default::default() }; // Compilation error, Person doesn't impl Default let pet = Pet { name: None, .. }; let pet = Pet { .. }; // Compilation error, name doesn't have a `const` default value let pet = Pet { ..Default::default() }; // Ok
-
Considerations around letting non-const expressions in the
struct
default are to be punted initially -
Considerations around making partial defaults a user definable feature are to be left for a future RFC (explicitly not adding a new
PartialDefault
trait, at least for now) -
Further conversation around "should a struct that has all default values set automagically impl
Default
?" and "should a struct that implsDefault
automagically work with..
?" is needed -
fn default<T: Default>(t: T) -> T { T::default() }
is tangential and independent of this RFC -
I will be basing the RFC on prior work that has been closed in the past due to lack of bandwidth.
Please everyone, let me know if there's any item that I have forgotten in this quick summary.