← Back to Pull requests

[RFC] Default field values #3681

Merged
estebank merged 1 files (1977 lines) on Nov 03, 2024 21:13 UTC
View on GitHub
estebank estebank commented on Aug 22, 2024 23:46 UTC
Author

Allow struct definitions to provide default values for individual fields and
thereby allowing those to be omitted from initializers. When deriving Default,
the provided values will then be used. For example:

#[derive(Default)]
struct Pet {
    name: Option<String>, // impl Default for Pet will use Default::default() for name
    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
}

Rendered

Tracking:

  • https://github.com/rust-lang/rust/issues/132162
  • Diff: 1977 lines (+1977 / -0) across 1 files Reviewer: compiler-errors Review duration: 104966m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.43) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.43 · 1977 lines diff across 1 files
    0.43
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.85 · 5 substantive comment(s)
    0.85
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    61 items
    compiler-errors compiler-errors commented on code on Aug 22, 2024 23:48 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1760 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42; // impl Default for Pet will use the literal 0 for age

        age: i128 = 42, // impl Default for Pet will use the literal 0 for age
    

    typo?

    estebank estebank commented on code on Aug 22, 2024 23:52 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1760 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42; // impl Default for Pet will use the literal 0 for age

    yep, carried it over from a 4 year old typo 🤦

    scottmcm scottmcm commented on code on Aug 22, 2024 23:53 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 0 for age

    typo?

        age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    

    compiler-errors compiler-errors commented on code on Aug 22, 2024 23:55 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.

    Unify is not a super accurate thing to call this in Rust. This should be "coerces to" throughout this RFC, to be consistent with the way type checking other consts work.

    scottmcm scottmcm commented on code on Aug 22, 2024 23:56 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:

    I'm not sure we should call this FRU, since there's no base object.

    My preference would be to say this RFC doesn't actually touch FRU at all, just expands struct field expressions (and the derives and such)...

    scottmcm scottmcm commented on code on Aug 22, 2024 23:57 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };

    ... at which point I'd probably just drop this example, because nothing in this RFC has changed it, so it's no different from the example on the line above.

    compiler-errors compiler-errors commented on code on Aug 22, 2024 23:58 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.

    Mentioning these first three points seems... redundant. Could you cut it from the RFC? It's also really accurate with how we type check ADTs.

    Type checking field initializers can be explained somewhat simply as a variant of FRU syntax, but where we pull the defaults from the constants in the struct definition.

    compiler-errors compiler-errors commented on code on Aug 22, 2024 23:59 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.

    I don't think these lemmas/proofs add very much value to the RFC either.

    This can be stated somewhat simply as: Path { fields, .. } is constant since the defaulted fields are initialized from constants. Or alternatively, I honestly think this can just be removed from the RFC.

    estebank estebank commented on code on Aug 23, 2024 00:00 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };

    Isn't there any value to state up-front that this hasn't changed for this case? But yeah, I'm ok with doing so: when writing ..val the same current rules apply, only the impl Default for Pet expansion has changed.

    compiler-errors compiler-errors commented on code on Aug 23, 2024 00:01 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.

    I also think section this can be cut from the RFC. I don't think we go into this much detail for new expressions, and it feels very very verbose to explain their dynamic semantics, especially because the only important part that users would care about is something like initialization order which wouldn't differ from FRU anyways.

    compiler-errors compiler-errors commented on code on Aug 23, 2024 00:04 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields
    +of `$s`):
    +
    +```rust
    +fn default() -> Self {
    +    $s { $f_i: Default::default(), .. }
    +}
    +```
    +
    +# Drawbacks
    +[drawbacks]: #drawbacks
    +
    +The usual drawback of increasing the complexity of the language applies.
    +However, the degree to which complexity is increased is not substantial.
    +
    +In particular, the syntax `Foo { .. }` mirrors the identical and already
    +existing pattern syntax. This makes the addition of `Foo { .. }` at worst
    +low-cost and potentially cost-free.
    +
    +The main complexity comes instead from introducing `field: Type = expr`.
    +However, as seen in the [prior-art], there are several widely-used languages
    +that have a notion of field / property / instance-variable defaults.
    +Therefore, the addition is intuitive and thus the cost is seen as limited. As
    +an implementation detail, `rustc` *already* parses `field: Type = expr`
    +purely to provide an appropriate diagnostic error:
    +
    +```
    +error: default values on `struct` fields aren't supported
    + --> src/lib.rs:2:28
    +  |
    +2 |     pub alpha: &'static str = "",
    +  |                            ^^^^^ help: remove this unsupported default value
    +```
    +
    +# Rationale and alternatives
    +[rationale-and-alternatives]: #rationale-and-alternatives
    +
    +Besides the given [motivation], there are some specific design choices
    +worthy of more in-depth discussion, which is the aim of this section.
    +
    +## Provided associated items as precedent
    +
    +While Rust does not have any support for default values for fields or for
    +formal parameters of functions, the notion of defaults are not foreign to Rust.
    +
    +Indeed, it is possible to provide default function bodies for `fn` items in
    +`trait` definitions. For example:
    +
    +```rust
    +pub trait PartialEq<Rhs: ?Sized = Self> {
    +    fn eq(&self, other: &Rhs) -> bool;
    +
    +    fn ne(&self, other: &Rhs) -> bool { // A default body.
    +        !self.eq(other)
    +    }
    +}
    +```
    +
    +In traits, `const` items can also be assigned a default value. For example:
    +
    +```rust
    +trait Foo {
    +    const BAR: usize = 42; // A default value.
    +}
    +```
    +
    +Thus, to extend Rust with a notion of field defaults is not an entirely alien
    +concept.
    +
    +## Pattern matching follows construction
    +
    +[dual]: https://en.wikipedia.org/wiki/Duality_(mathematics)
    +
    +In mathematics there is a notion of one thing being the *[dual]* of another.
    +Loosely speaking, duals are often about inverting something.
    +In Rust, one example of such an inversion is expressions and patterns.
    +
    +Expressions are used to *build up* and patterns *break apart*;
    +While it doesn't hold generally, a principle of language design both in Rust
    +and other languages with with pattern matching has been that the syntax for
    +patterns should, to the extent possible, follow that of expressions.
    +
    +For example:
    +
    ++ You can match on or build up a struct with `Foo { field }`.
    +  For patterns this will make `field` available as a binding
    +  while for expressions the binding `field` will be used to build a `Foo`.
    +
    +  For a tuple struct, `Foo(x)` will work both for construction and matching.
    +
    ++ If you want to be more flexible, both patterns and expressions permit
    +  `Foo { field: bar }`.
    +
    ++ You can use both `&x` to dereference and bind to `x` or
    +  construct a reference to `x`.
    +
    ++ An array can be constructed with `[a, b, c, d]` and the same is a valid
    +  pattern for destructuring an array.
    +
    +The reason why matching should follow construction is that it makes languages
    +easier to understand; you simply learn the expression syntax and then reuse
    +it to run the process in reverse.
    +
    +In some places, Rust could do a better job than it currently does of adhering to
    +this principle. In this particular case, the pattern syntax `Foo { a, b: c, .. }`
    +has no counterpart in the expression syntax. This RFC rectifies this by
    +permitting `Foo { a, b: c, .. }` as an expression syntax; this is identical
    +to the expression syntax and thus consistency has been gained.
    +
    +However, it is not merely sufficient to use the same syntax for expressions;
    +the semantics also have to be similar in kind for things to work out well.
    +This RFC argues that this is the case because in both contexts, `..` indicates
    +something partially ignorable is going on: "I am *destructuring*/*constructing*
    +this struct, and by the way there are some more fields I don't care about
    +*and let's* drop those* / *and let's fill in with default values*".
    +In a way, the use of `_` to mean both a catch-all pattern and type / value
    +placeholder is similar to `..`; in the case of `_` both cases indicate something
    +unimportant going on. For patterns, `_` matches everything and doesn't give
    +access to the value; for types, the placeholder is just an unbounded inference
    +variable.
    +
    +## On privacy

    It would be useful to cross-link to RFC 736 which explains privacy for FRU, and link that here: https://github.com/rust-lang/rfcs/blob/master/text/0736-privacy-respecting-fru.md

    scottmcm scottmcm commented on code on Aug 23, 2024 00:05 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```

    I don't think this RFC actually makes this possible.

    It would need an additional feature like allowing

    #[non_exhaustive(but_future_fields_will_have_defaults)]
    pub struct Config {
        pub width: u16,
        pub height: u16,
    }
    

    because #[non_exhaustive] is a license to add private fields without defaults today.

    And there are types today like

    #[non_exhaustive]
    pub struct Foo;
    

    that we really don't want to make creatable by Foo { .. } in other crates, since the reason they have that attribute today is to prevent such construction.

    ---

    I think that's fine, though: this RFC is useful without such an addition, and thus it can be left as future work.

    scottmcm scottmcm commented on code on Aug 23, 2024 00:08 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields
    +of `$s`):
    +
    +```rust
    +fn default() -> Self {
    +    $s { $f_i: Default::default(), .. }
    +}
    +```
    +
    +# Drawbacks
    +[drawbacks]: #drawbacks
    +
    +The usual drawback of increasing the complexity of the language applies.
    +However, the degree to which complexity is increased is not substantial.
    +
    +In particular, the syntax `Foo { .. }` mirrors the identical and already
    +existing pattern syntax. This makes the addition of `Foo { .. }` at worst
    +low-cost and potentially cost-free.

    One drawback that comes to mind is that it'll mean that a pattern Foo { .. } can match more things than just the expression Foo { .. }, because the pattern matches any value of the unmentioned fields, but the expression sets them to a particular value.

    That means that, with the unstable inline_const_pat, the arm const { Foo { .. } } => matches less than the arm Foo { .. } => (assuming a type like struct Foo { a: i32 = 1 }).

    I think I'm probably fine with that, but figured I'd mention it regardless.

    estebank estebank commented on code on Aug 23, 2024 00:11 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields
    +of `$s`):
    +
    +```rust
    +fn default() -> Self {
    +    $s { $f_i: Default::default(), .. }
    +}
    +```
    +
    +# Drawbacks
    +[drawbacks]: #drawbacks
    +
    +The usual drawback of increasing the complexity of the language applies.
    +However, the degree to which complexity is increased is not substantial.
    +
    +In particular, the syntax `Foo { .. }` mirrors the identical and already
    +existing pattern syntax. This makes the addition of `Foo { .. }` at worst
    +low-cost and potentially cost-free.

    That is an excellent call-out of a non-obvious interaction I hadn't accounted for.

    estebank estebank commented on code on Aug 23, 2024 00:13 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```

    Just to see if I get you right, you saying that this RFC should disallow #[non_exhaustive] and default fields on the same struct, and leave any interaction as an open question? I'm down with that.

    scottmcm scottmcm commented on code on Aug 23, 2024 00:13 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields
    +of `$s`):
    +
    +```rust
    +fn default() -> Self {
    +    $s { $f_i: Default::default(), .. }
    +}
    +```
    +
    +# Drawbacks
    +[drawbacks]: #drawbacks
    +
    +The usual drawback of increasing the complexity of the language applies.
    +However, the degree to which complexity is increased is not substantial.
    +
    +In particular, the syntax `Foo { .. }` mirrors the identical and already
    +existing pattern syntax. This makes the addition of `Foo { .. }` at worst
    +low-cost and potentially cost-free.
    +
    +The main complexity comes instead from introducing `field: Type = expr`.
    +However, as seen in the [prior-art], there are several widely-used languages
    +that have a notion of field / property / instance-variable defaults.
    +Therefore, the addition is intuitive and thus the cost is seen as limited. As
    +an implementation detail, `rustc` *already* parses `field: Type = expr`
    +purely to provide an appropriate diagnostic error:
    +
    +```
    +error: default values on `struct` fields aren't supported
    + --> src/lib.rs:2:28
    +  |
    +2 |     pub alpha: &'static str = "",
    +  |                            ^^^^^ help: remove this unsupported default value
    +```
    +
    +# Rationale and alternatives
    +[rationale-and-alternatives]: #rationale-and-alternatives
    +
    +Besides the given [motivation], there are some specific design choices
    +worthy of more in-depth discussion, which is the aim of this section.
    +
    +## Provided associated items as precedent
    +
    +While Rust does not have any support for default values for fields or for
    +formal parameters of functions, the notion of defaults are not foreign to Rust.
    +
    +Indeed, it is possible to provide default function bodies for `fn` items in
    +`trait` definitions. For example:
    +
    +```rust
    +pub trait PartialEq<Rhs: ?Sized = Self> {
    +    fn eq(&self, other: &Rhs) -> bool;
    +
    +    fn ne(&self, other: &Rhs) -> bool { // A default body.
    +        !self.eq(other)
    +    }
    +}
    +```
    +
    +In traits, `const` items can also be assigned a default value. For example:
    +
    +```rust
    +trait Foo {
    +    const BAR: usize = 42; // A default value.
    +}
    +```
    +
    +Thus, to extend Rust with a notion of field defaults is not an entirely alien
    +concept.
    +
    +## Pattern matching follows construction
    +
    +[dual]: https://en.wikipedia.org/wiki/Duality_(mathematics)
    +
    +In mathematics there is a notion of one thing being the *[dual]* of another.
    +Loosely speaking, duals are often about inverting something.
    +In Rust, one example of such an inversion is expressions and patterns.
    +
    +Expressions are used to *build up* and patterns *break apart*;
    +While it doesn't hold generally, a principle of language design both in Rust
    +and other languages with with pattern matching has been that the syntax for
    +patterns should, to the extent possible, follow that of expressions.
    +
    +For example:
    +
    ++ You can match on or build up a struct with `Foo { field }`.
    +  For patterns this will make `field` available as a binding
    +  while for expressions the binding `field` will be used to build a `Foo`.
    +
    +  For a tuple struct, `Foo(x)` will work both for construction and matching.
    +
    ++ If you want to be more flexible, both patterns and expressions permit
    +  `Foo { field: bar }`.
    +
    ++ You can use both `&x` to dereference and bind to `x` or
    +  construct a reference to `x`.
    +
    ++ An array can be constructed with `[a, b, c, d]` and the same is a valid
    +  pattern for destructuring an array.
    +
    +The reason why matching should follow construction is that it makes languages
    +easier to understand; you simply learn the expression syntax and then reuse
    +it to run the process in reverse.
    +
    +In some places, Rust could do a better job than it currently does of adhering to
    +this principle. In this particular case, the pattern syntax `Foo { a, b: c, .. }`
    +has no counterpart in the expression syntax. This RFC rectifies this by
    +permitting `Foo { a, b: c, .. }` as an expression syntax; this is identical
    +to the expression syntax and thus consistency has been gained.
    +
    +However, it is not merely sufficient to use the same syntax for expressions;
    +the semantics also have to be similar in kind for things to work out well.
    +This RFC argues that this is the case because in both contexts, `..` indicates
    +something partially ignorable is going on: "I am *destructuring*/*constructing*
    +this struct, and by the way there are some more fields I don't care about
    +*and let's* drop those* / *and let's fill in with default values*".
    +In a way, the use of `_` to mean both a catch-all pattern and type / value
    +placeholder is similar to `..`; in the case of `_` both cases indicate something
    +unimportant going on. For patterns, `_` matches everything and doesn't give
    +access to the value; for types, the placeholder is just an unbounded inference
    +variable.
    +
    +## On privacy
    +
    +This RFC specifies that when field defaults are specified, the desugaring
    +semantics of `Foo { .. }` spans `field: default_value` with the context in
    +which the type is defined as opposed to where `Foo { .. }` occurs.
    +In other words, the following is valid:
    +
    +```rust
    +pub mod alpha {
    +    pub struct Foo {
    +        field: u8 = 42,
    +    }
    +}
    +
    +use alpha::Foo;
    +
    +mod beta {
    +    // `field` isn't visible here.
    +    fn bar() -> Foo {
    +        Foo { .. } // OK!
    +    }
    +}
    +```
    +
    +By permitting the above snippet, you are able to construct a default value
    +for a type more ergonomically with `Foo { .. }`. Since it isn't possible for
    +functions in `beta` to access `field`'s value, the value `42` or any other
    +remains at all times private to `alpha`. Therefore, privacy, and by extension
    +soundness, is preserved.
    +
    +If a user wishes to keep other modules from constructing a `Foo` with
    +`Foo { .. }` they can simply add, or keep, one private field without a default.
    +Situations where this can be important include those where `Foo` is some token
    +for some resource and where fabricating a `Foo` may prove dangerous or worse
    +unsound. This is however no different than carelessly adding `#[derive(Default)]`.

    Or add #[non_exhaustive], as mentioned in my other comment.

    Might also be worth including a section here about why this isn't breaking:

    Allowing construction of not-non_exhaustive types with defaults for the private fields is non-breaking because no existing types have default values for fields, and thus accepting this feature won't allow users to create instances of any upstream types that they can't already.

    scottmcm scottmcm commented on code on Aug 23, 2024 00:16 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields
    +of `$s`):
    +
    +```rust
    +fn default() -> Self {
    +    $s { $f_i: Default::default(), .. }
    +}
    +```
    +
    +# Drawbacks
    +[drawbacks]: #drawbacks
    +
    +The usual drawback of increasing the complexity of the language applies.
    +However, the degree to which complexity is increased is not substantial.
    +
    +In particular, the syntax `Foo { .. }` mirrors the identical and already
    +existing pattern syntax. This makes the addition of `Foo { .. }` at worst
    +low-cost and potentially cost-free.
    +
    +The main complexity comes instead from introducing `field: Type = expr`.
    +However, as seen in the [prior-art], there are several widely-used languages
    +that have a notion of field / property / instance-variable defaults.
    +Therefore, the addition is intuitive and thus the cost is seen as limited. As
    +an implementation detail, `rustc` *already* parses `field: Type = expr`
    +purely to provide an appropriate diagnostic error:
    +
    +```
    +error: default values on `struct` fields aren't supported
    + --> src/lib.rs:2:28
    +  |
    +2 |     pub alpha: &'static str = "",
    +  |                            ^^^^^ help: remove this unsupported default value
    +```
    +
    +# Rationale and alternatives
    +[rationale-and-alternatives]: #rationale-and-alternatives
    +
    +Besides the given [motivation], there are some specific design choices
    +worthy of more in-depth discussion, which is the aim of this section.
    +
    +## Provided associated items as precedent
    +
    +While Rust does not have any support for default values for fields or for
    +formal parameters of functions, the notion of defaults are not foreign to Rust.
    +
    +Indeed, it is possible to provide default function bodies for `fn` items in
    +`trait` definitions. For example:
    +
    +```rust
    +pub trait PartialEq<Rhs: ?Sized = Self> {
    +    fn eq(&self, other: &Rhs) -> bool;
    +
    +    fn ne(&self, other: &Rhs) -> bool { // A default body.
    +        !self.eq(other)
    +    }
    +}
    +```
    +
    +In traits, `const` items can also be assigned a default value. For example:
    +
    +```rust
    +trait Foo {
    +    const BAR: usize = 42; // A default value.
    +}
    +```
    +
    +Thus, to extend Rust with a notion of field defaults is not an entirely alien
    +concept.
    +
    +## Pattern matching follows construction
    +
    +[dual]: https://en.wikipedia.org/wiki/Duality_(mathematics)
    +
    +In mathematics there is a notion of one thing being the *[dual]* of another.
    +Loosely speaking, duals are often about inverting something.
    +In Rust, one example of such an inversion is expressions and patterns.
    +
    +Expressions are used to *build up* and patterns *break apart*;
    +While it doesn't hold generally, a principle of language design both in Rust
    +and other languages with with pattern matching has been that the syntax for
    +patterns should, to the extent possible, follow that of expressions.
    +
    +For example:
    +
    ++ You can match on or build up a struct with `Foo { field }`.
    +  For patterns this will make `field` available as a binding
    +  while for expressions the binding `field` will be used to build a `Foo`.
    +
    +  For a tuple struct, `Foo(x)` will work both for construction and matching.
    +
    ++ If you want to be more flexible, both patterns and expressions permit
    +  `Foo { field: bar }`.
    +
    ++ You can use both `&x` to dereference and bind to `x` or
    +  construct a reference to `x`.
    +
    ++ An array can be constructed with `[a, b, c, d]` and the same is a valid
    +  pattern for destructuring an array.
    +
    +The reason why matching should follow construction is that it makes languages
    +easier to understand; you simply learn the expression syntax and then reuse
    +it to run the process in reverse.
    +
    +In some places, Rust could do a better job than it currently does of adhering to
    +this principle. In this particular case, the pattern syntax `Foo { a, b: c, .. }`
    +has no counterpart in the expression syntax. This RFC rectifies this by
    +permitting `Foo { a, b: c, .. }` as an expression syntax; this is identical
    +to the expression syntax and thus consistency has been gained.
    +
    +However, it is not merely sufficient to use the same syntax for expressions;
    +the semantics also have to be similar in kind for things to work out well.
    +This RFC argues that this is the case because in both contexts, `..` indicates
    +something partially ignorable is going on: "I am *destructuring*/*constructing*
    +this struct, and by the way there are some more fields I don't care about
    +*and let's* drop those* / *and let's fill in with default values*".
    +In a way, the use of `_` to mean both a catch-all pattern and type / value
    +placeholder is similar to `..`; in the case of `_` both cases indicate something
    +unimportant going on. For patterns, `_` matches everything and doesn't give
    +access to the value; for types, the placeholder is just an unbounded inference
    +variable.
    +
    +## On privacy
    +
    +This RFC specifies that when field defaults are specified, the desugaring
    +semantics of `Foo { .. }` spans `field: default_value` with the context in
    +which the type is defined as opposed to where `Foo { .. }` occurs.
    +In other words, the following is valid:
    +
    +```rust
    +pub mod alpha {
    +    pub struct Foo {
    +        field: u8 = 42,
    +    }
    +}
    +
    +use alpha::Foo;
    +
    +mod beta {
    +    // `field` isn't visible here.
    +    fn bar() -> Foo {
    +        Foo { .. } // OK!
    +    }
    +}
    +```
    +
    +By permitting the above snippet, you are able to construct a default value
    +for a type more ergonomically with `Foo { .. }`. Since it isn't possible for
    +functions in `beta` to access `field`'s value, the value `42` or any other
    +remains at all times private to `alpha`. Therefore, privacy, and by extension
    +soundness, is preserved.
    +
    +If a user wishes to keep other modules from constructing a `Foo` with
    +`Foo { .. }` they can simply add, or keep, one private field without a default.
    +Situations where this can be important include those where `Foo` is some token
    +for some resource and where fabricating a `Foo` may prove dangerous or worse
    +unsound. This is however no different than carelessly adding `#[derive(Default)]`.
    +
    +The feature *can* be stabilized *without* the privacy changes, turning the above
    +snippet into invalid code, in order to expedite the acceptance of this change,
    +leaving us to revisit this question at a later time once we get further real
    +world experience.
    +
    +## On `const` contexts
    +
    +To recap, the expression a default value is computed with must be constant one.
    +There are many reasons for this restriction:
    +
    ++ If *determinism* is not enforced, then just by writing the following snippet,
    +  the condition `x == y` may fail:
    +
    +  ```rust
    +  let x = Foo { .. };
    +  let y = Foo { .. };
    +  ```
    +
    +  This contributes to surprising behaviour overall.
    +
    +  Now you may object with an observation that if you replace `Foo { .. }` with
    +  `make_foo()` then a reader no longer know just from the syntactic form whether
    +  `x == y` is still upheld. This is indeed true. However, there is a general
    +  expectation in Rust that a function call may not behave deterministically.
    +  Meanwhile, for the syntactic form `Foo { .. }` and with default values,
    +  the whole idea is that they are something that doesn't require close attention.
    +
    ++ The broader class of problem that non-determinism highlights is that of
    +  *side*-effects. These effects wrt. program behaviour are prefixed with
    +  *"side"* because they happen without being communicated in the type system
    +  or more specifically in the inputs and outputs of a function.
    +
    +  In general, it is easier to do formal verification of programs that lack
    +  side-effects. While programming with Rust, requirements are usually not
    +  that demanding and robust. However, the same properties that make pure
    +  logic easier to formally verify also make for more *local reasoning*.
    +
    +  [reasoning footprint]: https://blog.rust-lang.org/2017/03/02/lang-ergonomics.html#implicit-vs-explicit
    +
    +  _By requring default field values to be `const` contexts, global reasoning
    +  can be avoided. Thus, the [reasoning footprint] for `Foo { .. }` is reduced._
    +
    ++ By restricting ourselves to `const` contexts, you can be sure that default
    +  literals have a degree of *cheapness*.
    +
    +  While `const` expressions form a turing complete language and therefore
    +  have no limits to their complexity other than being computable,
    +  these expressions are evaluated at *compile time*.
    +  Thus, *`const` expressions cannot have unbounded complexity at run-time*.
    +  At most, `const` expressions can create huge arrays and similar cases;
    +
    +  Ensuring that `Foo { .. }` remains relatively cheap is therefore important
    +  because there is a general expectation that literal expressions have a small
    +  and predictable run-time cost and are trivially predictable.
    +  This is particularly important for Rust since this is a language that aims
    +  to give a high degree of control over space and time as well as predictable
    +  performance characteristics.
    +
    ++ Keeping default values limited to `const` expressions ensures that if
    +  the following situation develops:
    +
    +  ```rust
    +  // Crate A:
    +  pub struct Foo {
    +      bar: u8 = const_expr,
    +  }
    +
    +  // Crate B:
    +  const fn baz() -> Foo {
    +      Foo { .. }
    +  }
    +  ```
    +
    +  then crate A cannot suddenly, and unawares, cause a semver breakage
    +  for crate B by replacing `const_expr` with `non_const_expr` since
    +  the compiler would reject such a change (see lemmas 1-2).
    +  Thus, enforcing constness gives a helping hand in respecting semantic version.
    +
    +  Note that if Rust would ever gain a mechanism to state that a
    +  function will not diverge, e.g.:
    +
    +  ```rust
    +  nopanic fn foo() -> u8 { 42 } // The weaker variant; more easily attainable.
    +  total fn bar() -> u8 { 24 } // No divergence, period.
    +  ```
    +
    +  then the same semver problem would manifest itself for those types of
    +  functions. However, Rust does not have any such enforcement mechanism
    +  right now and if it did, it is generally harder to ensure that a function
    +  is total than it is to ensure that it is deterministic; thus, while
    +  it is regrettable, this is an acceptable trade-off.
    +
    ++ Finally, note that `const fn`s, when coupled with planned future extensions,
    +  can become quite expressive. For example, it is already planned that `loop`s,
    +  `match`es, `let` statements, and `panic!(..)`s will be allowed.
    +  Another feasible extension in the future is allocation.
    +
    +  Therefore, constant expressions should be enough to satisfy most expressive
    +  needs.
    +
    +## Instead of `Foo { ..Default::default() }`
    +
    +As an alternative to the proposed design is either explicitly writing out
    +`..Default::default()` or extending the language such that `Foo { .. }` becomes
    +sugar for `Foo { ..Default::default() }`. While the latter idea does not satisfy
    +any of the [motivation] set out, the former does to a small extent.
    +
    +In particular, `Foo { .. }` as sugar slightly improves ergonomics.
    +However, it has some notable problems:
    +
    ++ Because it desugars to `Foo { ..Default::default() }`, it cannot be required
    +  that the expression is a constant one. This carries all the problems noted in
    +  the previous section on why default field values should be a `const` context.
    +
    ++ There is no way of implementing a `Default` implementation that has mandatory
    +  fields for users to specify during value construction.
    +
    ++ It provides zero improvements to the ergonomics of *specifying* defaults,
    +  only for using them. Arguably, the most important aspect of this RFC is
    +  not the syntax `Foo { .. }` but rather the ability to provide default values
    +  for field.
    +
    ++ By extension, the improvement to documentation clarity is lost.
    +
    ++ The trait `Default` must now become a `#[lang_item]`. This is a sign of
    +  increasing the overall magic in the system; meanwhile, this proposal makes
    +  the default values provided usable by other custom derive macros.
    +
    +Thus in conclusion, while desugaring `..` to `Default::default()` has lower cost,
    +it also provides significantly less value to the point of not being worth it.
    +
    +## `..` is useful as a marker
    +
    +One possible change to the current design is to permit filling in defaults
    +by simply writing `Foo {}`; in other words, `..` is simply dropped from the
    +expression.
    +
    +Among the benefits are:
    +
    ++ To enhance ergonomics of initialization further.
    +
    ++ To introduce less syntax.
    +
    ++ To be more in line with how other languages treat default values.
    +
    +Among the drawbacks are:
    +
    ++ The syntax `Foo { .. }` is no longer introduced to complement the identical
    +  pattern syntax. As aforementioned, destruction (and pattern matching)
    +  generally attempts to follow construction in Rust. Because of that,
    +  introducing `Foo { .. }` is essentially cost-free in terms of the complexity
    +  budget. It is arguably even cost-negative.
    +
    ++ By writing `Foo { .. }`, you have there is explicit indication that default
    +  values are being used; this enhances local reasoning further.
    +

    This RFC requires the `..` to get defaulted fields because it wants to continue to allow the workflow of intentionally *not* including `..` in the struct literal expression so that when a user adds a field they get compilation errors on every use -- just like is currently possible in patterns by not including `..` in the struct pattern.
    
    

    scottmcm scottmcm commented on code on Aug 23, 2024 00:17 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields
    +of `$s`):
    +
    +```rust
    +fn default() -> Self {
    +    $s { $f_i: Default::default(), .. }
    +}
    +```
    +
    +# Drawbacks
    +[drawbacks]: #drawbacks
    +
    +The usual drawback of increasing the complexity of the language applies.
    +However, the degree to which complexity is increased is not substantial.
    +
    +In particular, the syntax `Foo { .. }` mirrors the identical and already
    +existing pattern syntax. This makes the addition of `Foo { .. }` at worst
    +low-cost and potentially cost-free.
    +
    +The main complexity comes instead from introducing `field: Type = expr`.
    +However, as seen in the [prior-art], there are several widely-used languages
    +that have a notion of field / property / instance-variable defaults.
    +Therefore, the addition is intuitive and thus the cost is seen as limited. As
    +an implementation detail, `rustc` *already* parses `field: Type = expr`
    +purely to provide an appropriate diagnostic error:
    +
    +```
    +error: default values on `struct` fields aren't supported
    + --> src/lib.rs:2:28
    +  |
    +2 |     pub alpha: &'static str = "",
    +  |                            ^^^^^ help: remove this unsupported default value
    +```
    +
    +# Rationale and alternatives
    +[rationale-and-alternatives]: #rationale-and-alternatives
    +
    +Besides the given [motivation], there are some specific design choices
    +worthy of more in-depth discussion, which is the aim of this section.
    +
    +## Provided associated items as precedent
    +
    +While Rust does not have any support for default values for fields or for
    +formal parameters of functions, the notion of defaults are not foreign to Rust.
    +
    +Indeed, it is possible to provide default function bodies for `fn` items in
    +`trait` definitions. For example:
    +
    +```rust
    +pub trait PartialEq<Rhs: ?Sized = Self> {
    +    fn eq(&self, other: &Rhs) -> bool;
    +
    +    fn ne(&self, other: &Rhs) -> bool { // A default body.
    +        !self.eq(other)
    +    }
    +}
    +```
    +
    +In traits, `const` items can also be assigned a default value. For example:
    +
    +```rust
    +trait Foo {
    +    const BAR: usize = 42; // A default value.
    +}
    +```
    +
    +Thus, to extend Rust with a notion of field defaults is not an entirely alien
    +concept.
    +
    +## Pattern matching follows construction
    +
    +[dual]: https://en.wikipedia.org/wiki/Duality_(mathematics)
    +
    +In mathematics there is a notion of one thing being the *[dual]* of another.
    +Loosely speaking, duals are often about inverting something.
    +In Rust, one example of such an inversion is expressions and patterns.
    +
    +Expressions are used to *build up* and patterns *break apart*;
    +While it doesn't hold generally, a principle of language design both in Rust
    +and other languages with with pattern matching has been that the syntax for
    +patterns should, to the extent possible, follow that of expressions.
    +
    +For example:
    +
    ++ You can match on or build up a struct with `Foo { field }`.
    +  For patterns this will make `field` available as a binding
    +  while for expressions the binding `field` will be used to build a `Foo`.
    +
    +  For a tuple struct, `Foo(x)` will work both for construction and matching.
    +
    ++ If you want to be more flexible, both patterns and expressions permit
    +  `Foo { field: bar }`.
    +
    ++ You can use both `&x` to dereference and bind to `x` or
    +  construct a reference to `x`.
    +
    ++ An array can be constructed with `[a, b, c, d]` and the same is a valid
    +  pattern for destructuring an array.
    +
    +The reason why matching should follow construction is that it makes languages
    +easier to understand; you simply learn the expression syntax and then reuse
    +it to run the process in reverse.
    +
    +In some places, Rust could do a better job than it currently does of adhering to
    +this principle. In this particular case, the pattern syntax `Foo { a, b: c, .. }`
    +has no counterpart in the expression syntax. This RFC rectifies this by
    +permitting `Foo { a, b: c, .. }` as an expression syntax; this is identical
    +to the expression syntax and thus consistency has been gained.
    +
    +However, it is not merely sufficient to use the same syntax for expressions;
    +the semantics also have to be similar in kind for things to work out well.
    +This RFC argues that this is the case because in both contexts, `..` indicates
    +something partially ignorable is going on: "I am *destructuring*/*constructing*
    +this struct, and by the way there are some more fields I don't care about
    +*and let's* drop those* / *and let's fill in with default values*".
    +In a way, the use of `_` to mean both a catch-all pattern and type / value
    +placeholder is similar to `..`; in the case of `_` both cases indicate something
    +unimportant going on. For patterns, `_` matches everything and doesn't give
    +access to the value; for types, the placeholder is just an unbounded inference
    +variable.
    +
    +## On privacy
    +
    +This RFC specifies that when field defaults are specified, the desugaring
    +semantics of `Foo { .. }` spans `field: default_value` with the context in
    +which the type is defined as opposed to where `Foo { .. }` occurs.
    +In other words, the following is valid:
    +
    +```rust
    +pub mod alpha {
    +    pub struct Foo {
    +        field: u8 = 42,
    +    }
    +}
    +
    +use alpha::Foo;
    +
    +mod beta {
    +    // `field` isn't visible here.
    +    fn bar() -> Foo {
    +        Foo { .. } // OK!
    +    }
    +}
    +```
    +
    +By permitting the above snippet, you are able to construct a default value
    +for a type more ergonomically with `Foo { .. }`. Since it isn't possible for
    +functions in `beta` to access `field`'s value, the value `42` or any other
    +remains at all times private to `alpha`. Therefore, privacy, and by extension
    +soundness, is preserved.
    +
    +If a user wishes to keep other modules from constructing a `Foo` with
    +`Foo { .. }` they can simply add, or keep, one private field without a default.
    +Situations where this can be important include those where `Foo` is some token
    +for some resource and where fabricating a `Foo` may prove dangerous or worse
    +unsound. This is however no different than carelessly adding `#[derive(Default)]`.
    +
    +The feature *can* be stabilized *without* the privacy changes, turning the above
    +snippet into invalid code, in order to expedite the acceptance of this change,
    +leaving us to revisit this question at a later time once we get further real
    +world experience.
    +
    +## On `const` contexts
    +
    +To recap, the expression a default value is computed with must be constant one.
    +There are many reasons for this restriction:
    +
    ++ If *determinism* is not enforced, then just by writing the following snippet,
    +  the condition `x == y` may fail:
    +
    +  ```rust
    +  let x = Foo { .. };
    +  let y = Foo { .. };
    +  ```
    +
    +  This contributes to surprising behaviour overall.
    +
    +  Now you may object with an observation that if you replace `Foo { .. }` with
    +  `make_foo()` then a reader no longer know just from the syntactic form whether
    +  `x == y` is still upheld. This is indeed true. However, there is a general
    +  expectation in Rust that a function call may not behave deterministically.
    +  Meanwhile, for the syntactic form `Foo { .. }` and with default values,
    +  the whole idea is that they are something that doesn't require close attention.
    +
    ++ The broader class of problem that non-determinism highlights is that of
    +  *side*-effects. These effects wrt. program behaviour are prefixed with
    +  *"side"* because they happen without being communicated in the type system
    +  or more specifically in the inputs and outputs of a function.
    +
    +  In general, it is easier to do formal verification of programs that lack
    +  side-effects. While programming with Rust, requirements are usually not
    +  that demanding and robust. However, the same properties that make pure
    +  logic easier to formally verify also make for more *local reasoning*.
    +
    +  [reasoning footprint]: https://blog.rust-lang.org/2017/03/02/lang-ergonomics.html#implicit-vs-explicit
    +
    +  _By requring default field values to be `const` contexts, global reasoning
    +  can be avoided. Thus, the [reasoning footprint] for `Foo { .. }` is reduced._
    +
    ++ By restricting ourselves to `const` contexts, you can be sure that default
    +  literals have a degree of *cheapness*.
    +
    +  While `const` expressions form a turing complete language and therefore
    +  have no limits to their complexity other than being computable,
    +  these expressions are evaluated at *compile time*.
    +  Thus, *`const` expressions cannot have unbounded complexity at run-time*.
    +  At most, `const` expressions can create huge arrays and similar cases;
    +
    +  Ensuring that `Foo { .. }` remains relatively cheap is therefore important
    +  because there is a general expectation that literal expressions have a small
    +  and predictable run-time cost and are trivially predictable.
    +  This is particularly important for Rust since this is a language that aims
    +  to give a high degree of control over space and time as well as predictable
    +  performance characteristics.
    +
    ++ Keeping default values limited to `const` expressions ensures that if
    +  the following situation develops:
    +
    +  ```rust
    +  // Crate A:
    +  pub struct Foo {
    +      bar: u8 = const_expr,
    +  }
    +
    +  // Crate B:
    +  const fn baz() -> Foo {
    +      Foo { .. }
    +  }
    +  ```
    +
    +  then crate A cannot suddenly, and unawares, cause a semver breakage
    +  for crate B by replacing `const_expr` with `non_const_expr` since
    +  the compiler would reject such a change (see lemmas 1-2).
    +  Thus, enforcing constness gives a helping hand in respecting semantic version.
    +
    +  Note that if Rust would ever gain a mechanism to state that a
    +  function will not diverge, e.g.:
    +
    +  ```rust
    +  nopanic fn foo() -> u8 { 42 } // The weaker variant; more easily attainable.
    +  total fn bar() -> u8 { 24 } // No divergence, period.
    +  ```
    +
    +  then the same semver problem would manifest itself for those types of
    +  functions. However, Rust does not have any such enforcement mechanism
    +  right now and if it did, it is generally harder to ensure that a function
    +  is total than it is to ensure that it is deterministic; thus, while
    +  it is regrettable, this is an acceptable trade-off.
    +
    ++ Finally, note that `const fn`s, when coupled with planned future extensions,
    +  can become quite expressive. For example, it is already planned that `loop`s,
    +  `match`es, `let` statements, and `panic!(..)`s will be allowed.
    +  Another feasible extension in the future is allocation.
    +
    +  Therefore, constant expressions should be enough to satisfy most expressive
    +  needs.
    +
    +## Instead of `Foo { ..Default::default() }`
    +
    +As an alternative to the proposed design is either explicitly writing out
    +`..Default::default()` or extending the language such that `Foo { .. }` becomes
    +sugar for `Foo { ..Default::default() }`. While the latter idea does not satisfy
    +any of the [motivation] set out, the former does to a small extent.
    +
    +In particular, `Foo { .. }` as sugar slightly improves ergonomics.
    +However, it has some notable problems:
    +
    ++ Because it desugars to `Foo { ..Default::default() }`, it cannot be required
    +  that the expression is a constant one. This carries all the problems noted in
    +  the previous section on why default field values should be a `const` context.
    +
    ++ There is no way of implementing a `Default` implementation that has mandatory
    +  fields for users to specify during value construction.
    +
    ++ It provides zero improvements to the ergonomics of *specifying* defaults,
    +  only for using them. Arguably, the most important aspect of this RFC is
    +  not the syntax `Foo { .. }` but rather the ability to provide default values
    +  for field.
    +
    ++ By extension, the improvement to documentation clarity is lost.
    +
    ++ The trait `Default` must now become a `#[lang_item]`. This is a sign of
    +  increasing the overall magic in the system; meanwhile, this proposal makes
    +  the default values provided usable by other custom derive macros.
    +
    +Thus in conclusion, while desugaring `..` to `Default::default()` has lower cost,
    +it also provides significantly less value to the point of not being worth it.
    +
    +## `..` is useful as a marker
    +
    +One possible change to the current design is to permit filling in defaults
    +by simply writing `Foo {}`; in other words, `..` is simply dropped from the
    +expression.
    +
    +Among the benefits are:
    +
    ++ To enhance ergonomics of initialization further.
    +
    ++ To introduce less syntax.
    +
    ++ To be more in line with how other languages treat default values.
    +
    +Among the drawbacks are:
    +
    ++ The syntax `Foo { .. }` is no longer introduced to complement the identical
    +  pattern syntax. As aforementioned, destruction (and pattern matching)
    +  generally attempts to follow construction in Rust. Because of that,
    +  introducing `Foo { .. }` is essentially cost-free in terms of the complexity
    +  budget. It is arguably even cost-negative.
    +
    ++ By writing `Foo { .. }`, you have there is explicit indication that default
    +  values are being used; this enhances local reasoning further.
    +
    +## Named function arguments with default values
    +
    +A frequently requested feature is named function arguments. Today, the way to
    +design around the lack of these in the language are:
    +
    ++ Builder pattern
    ++ Defining a `struct` "bag-object" where optional fields are set, making users
    +  call functions in the following way:
    +  `foo(mandatory, Optionals { bar: 42, ..Default::default() })`
    ++ Provide multiple methods: `fn foo(mandatory)` *and* `fn foo_with_bar(mandatory, bar)`
    +
    +# Prior art
    +[prior-art]: #prior-art
    +
    +A prior version of this RFC, from which part of the contents in this version
    +were sourced, exists at https://github.com/Centril/rfcs/pull/19.
    +
    +This RFC was informed by a [lenghty discussion in internals.rust-lang.org](https://internals.rust-lang.org/t/pre-pre-rfc-syntactic-sugar-for-default-default/13234/75)
    +from a few years prior.
    +
    +Another prior RFC for the same feature is at https://github.com/rust-lang/rfcs/pull/1806.
    +
    +## Other languages
    +
    +This selection of languages are not exhaustive; rather, a few notable or
    +canonical examples are used instead.
    +
    +### Java
    +
    +In Java it is possible to assign default values, computed by any expression,
    +to an instance variable; for example, you may write:
    +
    +```java
    +class Main {
    +    public static void main(String[] args) {
    +        new Foo();
    +    }
    +
    +    public static int make_int() {
    +        System.out.println("I am making an int!");
    +        return 42;
    +    }
    +
    +    static class Foo {
    +        private int bar = Main.make_int();
    +    }
    +}
    +```
    +
    +When executing this program, the JVM will print the following to `stdout`:
    +
    +```
    +I am making an int!
    +```
    +
    +Two things are worth noting here:
    +
    +1. It is possible to cause arbitrary side effects in the expression that
    +   computes the default value of `bar`. This behaviour is unlike that which
    +   this RFC proposes.
    +
    +2. It is possible to construct a `Foo` which uses the default value of `bar`
    +   even though `bar` has `private` visibility. This is because default values
    +   act as syntactic sugar for how the default constructor `Foo()` should act.
    +   There is no such thing as constructors in Rust. However, the behaviour
    +   that Java has is morally equivalent to this RFC since literals are
    +   constructor-like and because this RFC also permits the usage of defaults
    +   for private fields where the fields are not visible.
    +
    +### Scala
    +
    +Being a JVM language, Scala builds upon Java and retains the notion of default
    +field values. For example, you may write:
    +
    +```scala
    +case class Person(name: String = make_string(), age: Int = 42)
    +
    +def make_string(): String = {
    +    System.out.println("foo");
    +    "bar"
    +}
    +
    +var p = new Person(age = 24);
    +System.out.println(p.name);
    +```
    +
    +As expected, this prints `foo` and then `bar` to the terminal.
    +
    +### Kotlin
    +
    +Kotlin is similar to both Java and Scala; here too can you use defaults:
    +
    +```kotlin
    +fun make_int(): Int {
    +    println("foo");
    +    return 42;
    +}
    +
    +class Person(val age: Int = make_int());
    +
    +fun main() {
    +    Person();
    +}
    +```
    +
    +Similar to Java and Scala, Kotlin does also permit side-effects in the default
    +values because both languages have no means of preventing the effects.
    +
    +### C#
    +
    +Another language with defaults of the object-oriented variety is C#.
    +The is behaviour similar to Java:
    +
    +```csharp
    +class Foo {
    +    int bar = 42;
    +}
    +```
    +
    +### C++
    +
    +Another language in the object-oriented family is C++. It also affords default
    +values like so:
    +
    +```cpp
    +#include <iostream>
    +
    +int make_int() {
    +    std::cout << "hello" << std::endl; // As in Java.
    +    return 42;
    +}
    +
    +class Foo {
    +    private:
    +        int bar = make_int();
    +    public:
    +        int get_bar() {
    +          return this->bar;
    +        }
    +};
    +
    +int main() {
    +    Foo x;
    +    std::cout << x.get_bar() << std::endl;
    +}
    +```
    +
    +In C++ it is still the case that the defaults are usable due to constructors.
    +And while the language has `constexpr` to enforce the ability to evaluate
    +something at compile time, as can be seen in the snippet above, no such
    +requirement is placed on default field values.
    +
    +### Swift
    +
    +[Swift]: https://docs.swift.org/swift-book/LanguageGuide/Initialization.html
    +
    +A language which is closer to Rust is [Swift], and it allows for default values:
    +
    +```swift
    +struct Person {
    +    var age = 42
    +}
    +```
    +
    +This is equivalent to writing:
    +
    +```swift
    +struct Person {
    +    var age: Int
    +    init() {
    +        age = 42
    +    }
    +}
    +```
    +
    +### Agda
    +
    +Having defaults for record fields is not the sole preserve of OO languages.
    +The pure, total, and dependently typed functional programming language Agda
    +also affords default values. For example, you may write:
    +
    +```agda
    +-- | Define the natural numbers inductively:
    +-- This corresponds to an `enum` in Rust.
    +data Nat : Set where
    +    zero : Nat
    +    suc  : Nat → Nat
    +
    +-- | Define a record type `Foo` with a field named `bar` typed at `Nat`.
    +record Foo : Set where
    +    bar : Nat
    +    bar = zero -- An optionally provided default value.
    +
    +myFoo : Foo
    +myFoo = record {} -- Construct a `Foo`.
    +```
    +
    +In contrast to languages such as Java, Agda does not have have a notion of
    +constructors. Rather, `record {}` fills in the default value.
    +
    +[strongly normalizing]: https://en.wikipedia.org/wiki/Normalization_property_(abstract_rewriting)
    +
    +Furthermore, Agda is a pure and [strongly normalizing] language and as such,
    +`record {}` may not cause any side-effects or even divergence. However,
    +as Agda employs monadic IO in the vein of Haskell,
    +it is possible to store a `IO Nat` value in the record:
    +
    +```agda
    +record Foo : Set where
    +    bar : IO Nat
    +    bar = do
    +        putStrLn "hello!"
    +        pure zero
    +```
    +
    +Note that this is explicitly typed as `bar : IO Nat` and that `record {}` won't
    +actually run the action. To do that, you will need take the `bar` value and run
    +it in an `IO` context.
    +
    +## Procedural macros
    +
    +There are a number of crates which to varying degrees afford macros for
    +default field values and associated facilities.
    +
    +### `#[derive(Builder)]`
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +Under this RFC, the code would be
    +
    +```rust
    +#[derive(Default, Debug, PartialEq)]
    +struct Lorem {
    +    pub ipsum: u32 = 42,
    +}
    +```
    +
    +
    +### `#[derive(Derivative)]`
    +
    +[`derivative`]: https://crates.io/crates/derivative
    +
    +The crate [`derivative`] provides the `#[derivative(Default)]` attribute.
    +With it, you may write:
    +
    +```rust
    +#[derive(Derivative)]
    +#[derivative(Default)]
    +struct RegexOptions {
    +    #[derivative(Default(value="10 * (1 << 20)"))]
    +    size_limit: usize,
    +    #[derivative(Default(value="2 * (1 << 20)"))]
    +    dfa_size_limit: usize,
    +    #[derivative(Default(value="true"))]
    +    unicode: bool,
    +}
    +
    +#[derive(Derivative)]
    +#[derivative(Default)]
    +enum Foo {
    +    #[derivative(Default)]
    +    Bar,
    +    Baz,
    +}
    +```
    +
    +Contrast this with the equivalent in the style of this RFC:
    +
    +```rust
    +#[derive(Default)]
    +struct RegexOptions {
    +    size_limit: usize = 10 * (1 << 20),
    +    dfa_size_limit: usize = 2 * (1 << 20),
    +    unicode: bool = true,
    +}
    +
    +#[derive(Default)]
    +enum Foo {
    +    #[default]
    +    Bar,
    +    Baz,
    +}
    +```
    +
    +There a few aspects to note:
    +
    +1. The signal to noise ratio is high as compared to the notation in this RFC.
    +  Substantial of syntactic overhead is accumulated to specify defaults.
    +
    +2. Expressions need to be wrapped in strings, i.e. `value="2 * (1 << 20)"`.
    +   While this is flexible and allows most logic to be embedded,
    +   the mechanism works poorly with IDEs and other tooling.
    +   Syntax highlighting also goes out of the window because the highlighter
    +   has no idea that the string included in the quotes is Rust code.
    +   It could just as well be a poem due to Shakespeare.
    +   At best, a highlighter could use some heuristic.
    +
    +3. The macro has no way to enforce that the code embedded in the strings are
    +   constant expressions. It might be possible to fix that but that might
    +   increase the logic of the macro considerably.
    +
    +4. Because the macro merely customizes how deriving `Default` works,
    +   it cannot provide the syntax `Foo { .. }`, interact with privacy,
    +   and it cannot provide defaults for `enum` variants.
    +
    +5. Like in this RFC, `derivative` allows you to derive `Default` for `enum`s.
    +   The syntax used in the macro is `#[derivative(Default)]` whereas the RFC
    +   provides the more ergonomic and direct notation `#[default]` in this RFC.
    +
    +6. To its credit, the macro provides `#[derivative(Default(bound=""))]`
    +   with which you can remove unnecessary bounds as well as add needed ones.
    +   This addresses a deficiency in the current deriving system for built-in
    +   derive macros. However, the attribute solves an orthogonal problem.
    +   The ability to specify default values would mean that `derivative` can
    +   piggyback on the default value syntax due to this RFC. The mechanism for
    +   removing or adding bounds can remain the same. Similar mechanisms could
    +   also be added to the language itself.
    +
    +### `#[derive(SmartDefault)]`
    +
    +[`smart-default`]: https://crates.io/crates/smart-default
    +
    +The [`smart-default`] provides `#[derive(SmartDefault)]` custom derive macro.
    +It functions similarly to `derivative` but is specialized for the `Default` trait.
    +With it, you can write:
    +
    +
    +```rust
    +#[derive(SmartDefault)]
    +struct RegexOptions {
    +    #[default = "10 * (1 << 20)"]
    +    size_limit: usize,
    +    #[default = "2 * (1 << 20)"]
    +    dfa_size_limit: usize,
    +    #[default = true]
    +    unicode: bool,
    +}
    +
    +#[derive(SmartDefault)]
    +enum Foo {
    +    #[default]
    +    Bar,
    +    Baz,
    +}
    +```
    +
    ++ The signal to noise ratio is still higher as compared to the notation in due
    +  to this RFC. The problems aforementioned from the `derivative` crate with
    +  respect to embedding Rust code in strings also persists.
    +
    ++ Points 2-4 regarding `derivative` apply to `smart-default` as well.
    +
    ++ The same syntax `#[default]` is used both by `smart-default` and by this RFC.
    +  While it may seem that this RFC was inspired by `smart-default`, this is not
    +  the case. Rather, this RFC's author came up with the notation independently.
    +  That suggests that the notation is intuitive since and a solid design choice.
    +
    ++ There is no trait `SmartDefault` even though it is being derived.
    +  This works because `#[proc_macro_derive(SmartDefault)]` is in fact
    +  not tied to any trait. That `#[derive(Serialize)]` refers to the same
    +  trait as the name of the macro is from the perspective of the language's
    +  static semantics entirely coincidental.
    +
    +  However, for users who aren't aware of this, it may seem strange that
    +  `SmartDefault` should derive for the `Default` trait.
    +
    +### `#[derive(new)]`
    +
    +[`derive-new`]: https://crates.io/crates/derive-new
    +
    +The [`derive-new`] crate provides the `#[derive(new)]` custom derive macro.
    +Unlike the two previous procedural macro crates, `derive-new` does not
    +provide implementations of `Default`. Rather, the macro facilitates the
    +generation of `MyType::new` constructors.
    +
    +For example, you may write:
    +
    +```rust
    +#[derive(new)]
    +struct Foo {
    +    x: bool,
    +    #[new(value = "42")]
    +    y: i32,
    +    #[new(default)]
    +    z: Vec<String>,
    +}
    +
    +Foo::new(true);
    +
    +#[derive(new)]
    +enum Enum {
    +    FirstVariant,
    +    SecondVariant(bool, #[new(default)] u8),
    +    ThirdVariant { x: i32, #[new(value = "vec![1]")] y: Vec<u8> }
    +}
    +
    +Enum::new_first_variant();
    +Enum::new_second_variant(true);
    +Enum::new_third_variant(42);
    +```
    +
    +Notice how `#[new(value = "vec![1]")`, `#[new(value = "42")]`,
    +and `#[new(default)]` are used to provide values that are then omitted
    +from the respective constructor functions that are generated.
    +
    +If you transcribe the above snippet as much as possible to the system proposed
    +in this RFC, you would get:
    +
    +```rust
    +struct Foo {
    +    x: bool,
    +    y: i32 = 42,
    +    z: Vec<String> = <_>::default(),
    +    //               --------------
    +    //               note: assuming some `impl const Default { .. }` mechanism.
    +}
    +
    +Foo { x: true };
    +
    +enum Enum {
    +    FirstVariant,
    +    SecondVariant(bool, u8), // See future possibilities.
    +    ThirdVariant { x: i32, y: Vec<u8> = vec![1] }
    +}
    +
    +Enum::FirstVariant;
    +Enum::SecondVariant(true, 0);
    +Enum::ThirdVariant { x: 42 };
    +```
    +
    +Relative to `#[derive(new)]`, the main benefits are:
    +
    ++ No wrapping code in strings, as noted in previous sections.
    ++ The defaults used can be mixed and matches; it works to request all defaults
    +  or just some of them.
    +
    +The constructor functions `new_first_variant(..)` are not provided for you.
    +However, it should be possible to tweak `#[derive(new)]` to interact with
    +this RFC so that constructor functions are regained if so desired.
    +
    +# Unresolved questions
    +[unresolved-questions]: #unresolved-questions
    +
    +1. What is the right interaction wrt. `#[non_exhaustive]`?
    +
    +   In particular, if given the following definition:
    +
    +   ```rust
    +   #[non_exhaustive]
    +   pub struct Config {
    +       pub height: u32,
    +       pub width: u32,
    +   }
    +   ```
    +
    +   it is possible to construct a `Config` like so:
    +
    +   ```rust
    +   let config = Config { width: 640, height: 480, .. };
    +   ```
    +
    +   then adding a field to `Config` can only happen iff that field
    +   is provided a default value.
    +
    +   This arrangement, while diminishing the usefulness of `#[non_exhaustive]`,
    +   makes the ruleset of the language simpler, more consistent, and also
    +   simplifies type checking as `#[non_exhaustive]` is entirely ignored
    +   when checking `Foo { fields, .. }` expressions.
    +
    +   As an alternative, users who desire the semantics described above can
    +   omit `#[non_exhaustive]` from their type and instead add a private
    +   defaulted field that has a ZST.
    +
    +   Resolving this question may be deferred to stabilization of either
    +   `#[non_exhaustive]` or field defaults, whichever comes last.

    Looks like it's field defaults that came last :P

    max-niederman max-niederman commented on code on Aug 23, 2024 00:23 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust

    I think it's worth also comparing against derive macros like typed-builder, which at least in my experience are a very common solution to this problem.

    scottmcm scottmcm commented on code on Aug 23, 2024 00:25 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```

    I was thinking that defaults would still be allowed, but the type would remain unconstructable from outside the defining crate. That way you can still use things like a default on PhantomData on internal, non_exhaustive types.

    Given that

    #[non_exhaustive]
    pub struct Foo;
    

    is commonly used to write a type that cannot be constructed outside the crate (replacing the old pub struct Foo(()); way of writing this), I don't think we can ever say that any non_exhaustive types are constructible outside the defining crate without the defining crate opting-in to that somehow. Telling everyone they have to change back to having a private field is a non-starter, in my opinion.

    But I'd also be fine with saying that you just can't mix them yet, and make decisions about it later.

    scottmcm scottmcm commented on code on Aug 23, 2024 00:28 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };

    Mostly if I didn't already know what the RFC was going to say, I'd read "FRU" here and think that this RFC was also going to fix all the complaints people have with FRU. It's just about expectation-setting.

    Having an example saying that it doesn't change FRU at all would also meet that suggestion.

    But this is also the summary, so it might be good to instead have that elsewhere in the RFC, because it's not exactly the kind of thing that I think of as being critical in the summary.

    max-niederman max-niederman commented on code on Aug 23, 2024 00:28 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,

    The nomicon no longer says this.

    max-niederman max-niederman commented on code on Aug 23, 2024 00:31 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]

    Nit: #[structopt(default_value_t = 42)] would be the more comparable structopt option.

    compiler-errors compiler-errors commented on code on Aug 23, 2024 00:32 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:

    I think it's useful if the RFC draws parallel to the FRU syntax whenever possible, to avoid needing to re-explain things like how struct initializer expressions are type checked (especially bc going into the detail of how it actually works means this RFC is gonna get it wrong). But it's worthwhile calling this something different than FRU.

    scottmcm scottmcm commented on code on Aug 23, 2024 00:34 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR:
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:

    Agree in the reference section, C-E, but not in the summary.

    max-niederman max-niederman commented on code on Aug 23, 2024 00:37 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],

    You refer to this later as using Vec::new().

        args: Vec<String> = Vec::new(),
    

    max-niederman max-niederman commented on code on Aug 23, 2024 00:52 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must

    Don't you mean each field f in the referenced struct or enum variant?

    max-niederman max-niederman commented on code on Aug 23, 2024 00:57 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where

    If this stays in the RFC (I agree with @compiler-errors that it probably shouldn't), these two cases can be unified by letting τ have zero or more fields specified rather than one or more.

    max-niederman max-niederman commented on code on Aug 23, 2024 01:02 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```
    +
    +## Defaults for `enum`s
    +
    +The ability to give fields default values is not limited to `struct`s.
    +Fields of `enum` variants can also be given defaults (16):
    +
    +```rust
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    }
    +}
    +```
    +
    +Given these defaults, you can then proceed to initialize `Ingredient`s
    +as you did with `struct`s (17):
    +
    +```rust
    +let sallad_parts = vec![
    +    Ingredient::Tomato { taste: Yummy, .. },
    +    Ingredient::Tomato { taste: Delicious, color: Color::Green, },
    +    Ingredient::Onion { .. },
    +];
    +```
    +
    +Note that `enum` variants have public fields and in today's Rust,
    +this cannot be controlled with visibility modifiers on variants.
    +
    +Furthermore, when `#[non_exhaustive]` is specified directly on an `enum`,
    +it has no interaction with the defaults values and the ability to construct
    +variants of said enum. However, as specified by [RFC 2008], `#[non_exhaustive]`
    +is permitted on variants. When that occurs, the behaviour is the same as if
    +it had been attached to a `struct` with the same fields.
    +
    +### Interaction with `#[default]`
    +
    +[`#[default]`]: https://github.com/rust-lang/rfcs/pull/3107
    +
    +It is possible today to specify a [`#[default]` variant] in an enum so that it
    +can be `#[derive(Default)]`. A variant marked with `#[default]` will use
    +defaulted fields when present.
    +
    +```rust
    +#[derive(Default)]
    +enum Ingredient {
    +    Tomato {
    +        color: Color = Color::Red,
    +        taste: TasteQuality,
    +    },
    +    Onion {
    +        color: Color = Color::Yellow,
    +    },
    +    #[default]
    +    Lettuce {
    +        color: Color = Color::Green,
    +    },
    +}
    +```
    +
    +Now the compiler does know that `Ingredient::Lettuce` should be considered
    +the default and will accordingly generate an appropriate implementation of
    +`Default for Ingredient` (19):
    +
    +```rust
    +impl Default for Ingredient {
    +    fn default() -> Self {
    +        Ingredient::Lettuce {
    +            color: Color::Green,
    +        }
    +    }
    +}
    +```
    +
    +## Defaults on tuple `struct`s and tuple `enum` variants
    +
    +Default values are only allowed on named fields. There is no syntax provided for
    +tuple types like `struct S(i32)` or `enum E { V(i32), }`.
    +
    +# Reference-level explanation
    +[reference-level-explanation]: #reference-level-explanation
    +
    +## Field default values
    +
    +### Grammar
    +
    +Let the grammar of record fields in `struct`s and `enum` variants be defined
    +like so (in the `.lyg` notation):
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type;
    +```
    +
    +Then, `RecordField` is changed into:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type { "=" def:Expr }?;
    +```
    +
    +Further, given the following partial definition for the expression grammar:
    +
    +```rust
    +Expr = attrs:OuterAttr* kind:ExprKind;
    +ExprKind =
    +  | ...
    +  | Struct:{ path:Path "{" attrs:InnerAttr* fields:StructExprFieldsAndBase "}" }
    +  ;
    +
    +StructExprFieldsAndBase =
    +  | Fields:{ fields:StructExprField* % "," ","? }
    +  | Base:{ ".." base:Expr }
    +  | FieldsAndBase:{ fields:StructExprField+ % "," "," ".." base:Expr }
    +  ;
    +StructExprField = attrs:OuterAttr* kind:StructExprFieldKind;
    +StructExprFieldKind =
    +  | Shorthand:IDENT
    +  | Explicit:{ field:FieldName ":" expr:Expr }
    +  ;
    +```
    +
    +the rule `StructExprFieldsAndBase` is extended with:
    +
    +```rust
    +StructExprFieldsAndBase =| FieldsAndDefault:{ fields:StructExprField+ % "," "," ".." };
    +```
    +
    +### Static semantics
    +
    +#### Defining defaults
    +
    +Given a `RecordField` where the default is specified, i.e.:
    +
    +```rust
    +RecordField = attrs:OuterAttr* vis:Vis? name:IDENT ":" ty:Type "=" def:Expr;
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. The expression `def` must be a constant expression.
    +
    +2. The expression `def` must unify with the type `ty`.
    +
    +When lints check attributes such as `#[allow(lint_name)]` are placed on a
    +`RecordField`, it also applies to `def` if it exists.
    +
    +#### Initialization expressions
    +
    +Given an expression `τ` of the form (e.g. `Foo { x: 1, .. }`):
    +
    +```rust
    +path:Path "{" attrs:InnerAttr* fields:StructExprField+ % "," "," ".." "}"
    +```
    +
    +all the following rules apply when type-checking:
    +
    +1. All `fields` in `τ` mentioned must exist in the `struct` or `enum` variant
    +   referenced by `path`. No field in `fields` may be mentioned twice.
    +
    +2. For each `field: expr` pair in `fields` of `τ`,
    +   `expr` must unify with the type of `field` in the `struct`
    +   or `enum` variant referenced by `path`.
    +
    +3. For each `field: expression` pair in `fields` of `τ`,
    +   `field` must be visible in the context which `τ` occurs in.
    +
    +4. For each field `f` in `τ` *not* mentioned in `fields`, a default value must
    +   exist for `f` in the `struct` or `enum` variant referenced by `path`.
    +
    +---------------------
    +
    +**Lemma 1:** If `τ` is of a type `σ` where `σ: Sync`, and if all `field: expr`
    +has an `expr` component which is a valid constant expression, then `τ` is
    +also a valid constant expression.
    +
    +**Proof:** It trivially holds that if all `expr`s in `τ` are
    +constant expressions and all default values for fields omitted
    +are also constant expressions, then `τ` is a constant expression.
    +
    +**Lemma 2:** If an expression `x` of form `Path { .. }` is of a type `σ` where
    +`σ: Sync`, then `x` is a constant expression.
    +
    +**Proof:** `x` is a special case of `τ` with all fields according to the default
    +values. Since there are no explicitly provided fields, by Lemma 1 it holds.
    +
    +### Dynamic semantics
    +
    +Given a well-formed expression `τ` according to the aforementioned form,
    +the operational semantics is the same as the semantics of an expression
    +`path { new_fields }` with `new_fields = fields ∪ default_fields` where:
    +
    ++ `∪` computes the left-biased union where equal elements are determined
    +  solely on equality of field names.
    +
    ++ `fields` are the set of explicitly given `field: expr` pairs.
    +
    ++ `default_fields` are the fields in `τ`'s data-type or variant which
    +  have provided default values.
    +
    +## `#[derive(Default)]`
    +
    +When generating an implementation of `Default` for a `struct` named `$s` on
    +which `#[derive(Default)]` has been attached, the compiler will omit all fields
    +which have default values provided in the `struct`. The the associated function
    +`default` shall then be defined as (where `$f_i` denotes a vector of the fields

    Nit:

    `default` shall then be defined as (where `$f_i` denotes the `i`-th field
    

    clarfonthey clarfonthey commented on code on Aug 23, 2024 01:03 UTC
    Code Review
    text/0000-default-field-values.md:1
    @@ -0,0 +1,1767 @@
    +- Feature Name: `default_field_values`
    +- Start Date: 2024-08-22
    +- RFC PR: https://github.com/rust-lang/rfcs/pull/3681
    +- Rust Issue:
    +
    +# Summary
    +[summary]: #summary
    +
    +Allow `struct` definitions to provide default values for individual fields and
    +thereby allowing those to be omitted from initializers. When deriving `Default`,
    +the provided values will then be used. For example:
    +
    +```rust
    +#[derive(Default)]
    +struct Pet {
    +    name: Option<String>, // impl Default for Pet will use Default::default() for name
    +    age: i128 = 42, // impl Default for Pet will use the literal 42 for age
    +}
    +```
    +
    +These can then be used in the following way with the Functional Record Update syntax, with no value:
    +
    +```rust
    +// Pet { name: Some(""), age: 42 }
    +let _ = Pet { name: Some(String::new()), .. }
    +// Compilation error: `name` needs to be specified
    +let _ = Pet { .. }
    +// Derived `Default` uses struct field defaults if present:
    +// Pet { name: None, age: 42 }
    +let _ = Pet::default();
    +// Pet { name: None, age: 42 }
    +let _ = Pet { ..Pet::default() };
    +```
    +
    +# Motivation
    +[motivation]: #motivation
    +
    +## Boilerplate reduction
    +
    +### For `struct`s
    +
    +[FRU]: https://doc.rust-lang.org/1.31.0/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
    +
    +Rust allows you to create an instance of a `struct` using the struct literal
    +syntax `Foo { bar: expr, baz: expr }`. To do so, all fields in the `struct`
    +must be assigned a value. This makes it inconvenient to create large `struct`s
    +whose fields usually receive the same values. Struct literals also cannot be
    +used to initialize `struct`s with fields which are inaccessible due to privacy.
    +*[Functional record updates (FRU)][FRU]* can reduce noise when a `struct`
    +derives `Default`, but are also invalid when the `struct` has inaccessible
    +fields and do not allow the creation of an `impl` where *some* fields are
    +mandatory.
    +
    +To work around these shortcomings, you can create constructor functions:
    +
    +```rust
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +
    +let foo = Foo::new("Hello", 42);
    +```
    +
    +[`process::Command`]: https://doc.rust-lang.org/stable/std/process/struct.Command.html
    +
    +The problem with a constructor is that you need one for each combination
    +of fields a caller can supply. To work around this, you can use builders,
    +such as [`process::Command`] in the standard library.
    +Builders enable more advanced initialization, but require additional boilerplate.
    +To represent the difference, we can see the dramatic syntactical increase for
    +semantically small changes:
    +
    +```rust
    +// All fields are mandatory
    +struct Foo {
    +    alpha: &'static str,
    +    beta: bool,
    +    gamma: i32,
    +}
    +```
    +
    +```rust
    +impl Foo {
    +    /// Constructs a `Foo`.
    +    fn new(alpha: &'static str, gamma: i32) -> Self {
    +        Self {
    +            alpha,
    +            beta: true,
    +            gamma
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +// A builder type that is able to construct a `Foo`, but that will fail at runtime if a field is
    +// missing.
    +#[derive(Default)]
    +struct FooBuilder {
    +    pub alpha: Option<&'static str>,
    +    pub beta: Option<bool>,
    +    pub gamma: Option<i32>,
    +}
    +
    +impl FooBuilder {
    +    fn new() -> Self {
    +        FooBuilder::default()
    +    }
    +    fn set_alpha(&mut self, alpha: &'static str) -> &mut Self {
    +        self.alpha = Some(alpha);
    +        self
    +    }
    +    fn set_beta(&mut self, beta: &'static str) -> &mut Self {
    +        self.beta = Some(beta);
    +        self
    +    }
    +    fn set_gamma(&mut self, gamma: &'static str) -> &mut Self {
    +        self.gamma = Some(gamma);
    +        self
    +    }
    +
    +    fn build(self) -> Foo {
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0),
    +        }
    +    }
    +}
    +```
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32,
    +}
    +
    +// A builder type that is able to construct a `Foo`, but that will fail at compile time if a field
    +// is missing.
    +#[derive(Default)]
    +pub struct FooBuilder<const A: bool, const B: bool, const G: bool> {
    +    alpha: Option<&'static str>,
    +    beta: Option<bool>,
    +    gamma: Option<i32>,
    +}
    +
    +// We provide this `impl` on its own so that `FooBuilder::new()` will work without specifying the
    +// const parameters.
    +impl FooBuilder<false, false, false> {
    +    fn new() -> FooBuilder<false, false, false> {
    +        FooBuilder::default()
    +    }
    +}
    +
    +// The fields can only be set once. Calling `set_alpha` twice will result in a compilation error.
    +impl<const B: bool, const G: bool> FooBuilder<false, B, G> {
    +    fn set_alpha(mut self, alpha: &'static str) -> FooBuilder<true, B, G> {
    +        self.alpha = Some(alpha);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const G: bool> FooBuilder<A, false, G> {
    +    fn set_beta(mut self, beta: bool) -> FooBuilder<A, true, G> {
    +        self.beta = Some(beta);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +impl<const A: bool, const B: bool> FooBuilder<A, B, false> {
    +    fn set_gamma(mut self, gamma: i32) -> FooBuilder<A, B, true> {
    +        self.gamma = Some(gamma);
    +        unsafe { std::mem::transmute(self) }
    +    }
    +}
    +// If any field is optional, 
    +impl<const G: bool> FooBuilder<true, true, G> {
    +    fn build(self) -> Foo { // can only be called if all fields have been set
    +        Foo {
    +            alpha: self.alpha.unwrap(),
    +            beta: self.beta.unwrap(),
    +            gamma: self.gamma.unwrap_or(0), // This is an optional field with a default.
    +        }
    +    }
    +}
    +
    +fn main() {
    +    let _ = FooBuilder::new()
    +        .set_alpha("")
    +        .set_beta(false) // If we comment this out, it will no longer compile.
    +        .set_gamma(42) // If we comment this out, it will still compile.
    +        .build();
    +}
    +```
    +
    +All of the above can be represented with the exact same results with struct
    +field default values, but with much less boilerplate:
    +
    +```rust
    +pub struct Foo {
    +    pub alpha: &'static str,
    +    pub beta: bool,
    +    pub gamma: i32 = 0,
    +}
    +
    +fn main() {
    +    let _ = Foo {
    +        alpha: "",
    +        beta: false,
    +        ..
    +    };
    +}
    +```
    +
    +The builder pattern is quite common in the Rust ecosystem, but as shown above its need is greatly
    +reduced with `struct` field defaults.
    +
    +### `PhantomData` ergonomics
    +
    +[nomicon]: https://doc.rust-lang.org/nightly/nomicon/phantom-data.html
    +[PhantomData]: https://doc.rust-lang.org/stable/std/marker/struct.PhantomData.html
    +
    +Say that you want to define our own `Vec<T>` type. As the [nomicon] says,
    +you need to use [PhantomData] to make sure that drop-checking is sound like so:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T>,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            _marker: PhantomData,
    +        }
    +    }
    +}
    +```
    +
    +Here, `_marker: PhantomData` is just provided to satisfy the compiler.
    +`PhantomData` carries no useful information since it is a ZST.
    +Therefore, the result of having to add a field of type `PhantomData`
    +is a regression to ergonomics throughout. With default values you can
    +improve the situation slightly and provide the value in a single place:
    +
    +```rust
    +use std::marker::PhantomData;
    +
    +struct Vec<T> {
    +    data: *const T, // *const for variance!
    +    len: usize,
    +    cap: usize,
    +    _marker: PhantomData<T> = PhantomData,
    +}
    +```
    +
    +You then go on to define some operations for `Vec<T>`:
    +
    +```rust
    +impl<T> Vec<T> {
    +    pub fn new() -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +
    +    pub fn with_capacity(capacity: usize) -> Self {
    +        Self {
    +            // other fields...
    +            ..
    +        }
    +    }
    +}
    +```
    +
    +## `#[derive(Default)]` in more cases
    +
    +The `#[derive(..)]` ("custom derive") mechanism works by defining procedural
    +*macros*. Because they are macros, these operate on abstract *syntax* and
    +don't have more information available. Therefore, when you `#[derive(Default)]`
    +on a data type definition as with:
    +
    +```rust
    +#[derive(Default)]
    +struct Foo {
    +    bar: u8,
    +    baz: String,
    +}
    +```
    +
    +it only has the immediate "textual" definition available to it.
    +
    +Because Rust currently does not have an in-language way to define default values,
    +you cannot `#[derive(Default)]` in the cases where you are not happy with the
    +natural default values that each field's type provides. By extending the syntax
    +of Rust such that default values can be provided, `#[derive(Default)]` can be
    +used in many more circumstances and thus boilerplate is further reduced.  The
    +addition of a single field, expands the code written by the `struct` author from
    +a single `derive` line to a whole `Default` `impl`, which becomes more verbose
    +linearly with the number of fields.
    +
    +## Usage by other `#[derive(..)]` macros
    +
    +[`serde`]: https://serde.rs/attributes.html
    +
    +Custom derive macros exist that have a notion of or use default values.
    +
    +### `serde`
    +
    +For example, the [`serde`] crate provides a `#[serde(default)]` attribute that
    +can be used on `struct`s, and fields. This will use the field's or type's
    +`Default` implementations. This works well with field defaults; `serde` can
    +either continue to rely on `Default` implementations in which case this RFC
    +facilitates specification of field defaults; or it can directly use the default
    +values provided in the type definition.
    +
    +### `structopt`
    +
    +Another example is the `structopt` crate with which you can write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed", default_value = "42")]
    +    speed: f64,
    +    ...
    +}
    +```
    +
    +By having default field values in the language, `structopt` could let you write:
    +
    +```rust
    +#[derive(Debug, StructOpt)]
    +#[structopt(name = "example", about = "An example of StructOpt usage.")]
    +struct Opt {
    +    /// Set speed
    +    #[structopt(short = "s", long = "speed")]
    +    speed: f64 = 42,
    +    ...
    +}
    +```
    +
    +### `derive_builder`
    +
    +[`derive_builder`]: https://docs.rs/derive_builder/0.7.0/derive_builder/#default-values
    +
    +A third example comes from the crate [`derive_builder`]. As the name implies,
    +you can use it to `#[derive(Builder)]`s for your types. An example is:
    +
    +```rust
    +#[derive(Builder, Debug, PartialEq)]
    +struct Lorem {
    +    #[builder(default = "42")]
    +    pub ipsum: u32,
    +}
    +```
    +
    +### Conclusion
    +
    +As seen in the previous sections, rather than make deriving `Default`
    +more magical, by allowing default field values in the language,
    +user-space custom derive macros can make use of them.
    +
    +# Guide-level explanation
    +[guide-level-explanation]: #guide-level-explanation
    +
    +## Providing field defaults
    +
    +Consider a data-type such as (1):
    +
    +```rust
    +pub struct Probability {
    +    value: f32,
    +}
    +```
    +
    +You'd like encode the default probability value to be `0.5`;
    +With this RFC now you can provide such a default directly where `Probability`
    +is defined like so (2):
    +
    +```rust
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, you can now construct a `Probability` with a struct
    +initializer and leave `value` out to use the default (3):
    +
    +```rust
    +let prob = Probability { .. };
    +```
    +
    +## Deriving `Default`
    +
    +Previously, you might have instead implemented the `Default` trait like so (4):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { value: 0.5 }
    +    }
    +}
    +```
    +
    +You can now shorten this to (5):
    +
    +```rust
    +impl Default for Probability {
    +    fn default() -> Self {
    +        Self { .. }
    +    }
    +}
    +```
    +
    +However, since you had specified `value: f32 = 0.5` in the definition of
    +`Probability`, you can take advantage of that to write the more simpler
    +and more idiomatic (6):
    +
    +```rust
    +#[derive(Default)]
    +pub struct Probability {
    +    value: f32 = 0.5,
    +}
    +```
    +
    +Having done this, a `Default` implementation equivalent to the one in (5)
    +will be generated for you.
    +
    +## More fields
    +
    +As you saw in the [summary], you are not limited to a single field and all
    +fields need not have any defaults associated with them. Instead, you can freely
    +mix and match. Given the definition of `LaunchCommand` from the [motivation] (7):
    +
    +```rust
    +struct LaunchCommand {
    +    cmd: String,
    +    args: Vec<String> = vec![],
    +    some_special_setting: Option<FancyConfig> = None,
    +    setting_most_people_will_ignore: Option<FlyMeToTheMoon> = None,
    +}
    +```
    +
    +you can omit all fields but `cmd` (8):
    +
    +```rust
    +let ls_cmd = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    ..
    +};
    +```
    +
    +You can also elect to override the provided defaults (9):
    +
    +```rust
    +let ls_cmd2 = LaunchCommand {
    +    cmd: "ls".to_string(),
    +    args: vec!["-lah".to_string()],
    +    some_special_setting: make_special_setting(),
    +    // setting_most_people_will_ignore is still defaulted.
    +    ..
    +};
    +```
    +
    +## Default fields values are [`const` context]s
    +
    +[`const` context]: https://github.com/rust-lang-nursery/reference/blob/66ef5396eccca909536b91cad853f727789c8ebe/src/const_eval.md#const-context
    +
    +As you saw in (7), `Vec::new()`, a function call, was used.
    +However, this assumes that `Vec::new` is a *`const fn`*. That is, when you
    +provide a default value `field: Type = value`, the given `value` must be a
    +*constant expression* such that it is valid in a [`const` context].
    +Therefore, you cannot write something like (10):
    +
    +```rust
    +fn launch_missilies() -> Result<(), LaunchFailure> {
    +    authenticate()?;
    +    begin_launch_sequence()?;
    +    ignite()?;
    +    Ok(())
    +}
    +
    +struct BadFoo {
    +    bad_field: u8 = {
    +        launch_missilies().unwrap();
    +        42
    +    },
    +}
    +```
    +
    +Since launching missiles interacts with the real world and has *side-effects*
    +in it, it is not possible to do that in a `const` context since it may violate
    +deterministic compilation.
    +
    +## Privacy interactions
    +
    +In examples thus far, initialization literal expressions `Foo { bar, .. }` have
    +been used in the same module as where the constructed type was defined in.
    +
    +Let's now consider a scenario where this is not the case (11):
    +
    +```rust
    +pub mod foo {
    +    pub struct Alpha {
    +        beta: u8 = 42,
    +        gamma: bool = true,
    +    }
    +}
    +
    +mod bar {
    +    fn baz() {
    +        let x = Alpha { .. };
    +    }
    +}
    +```
    +
    +Despite `foo::bar` being in a different module than `foo::Alpha` and despite
    +`beta` and `gamma` being private to `foo::bar`, a Rust compiler will accept
    +the above snippet. It is legal because when `Alpha { .. }` expands to
    +`Alpha { beta: 42, gamma: true }`, the fields `beta` and `gamma` are considered
    +in the context of `foo::Alpha`'s *definition site* rather than `bar::baz`'s
    +definition site.
    +
    +## `#[non_exhaustive]` interactions
    +
    +[RFC 2008]: https://github.com/rust-lang/rfcs/blob/master/text/2008-non-exhaustive.md#structs-1
    +
    +[RFC 2008] introduced the attribute `#[non_exhaustive]` that can be placed
    +on `struct`, `enum`, and `enum` variants. The RFC notes that upon defining
    +a `struct` in *crate A* such as (12):
    +
    +```rust
    +#[non_exhaustive]
    +pub struct Config {
    +    pub width: u16,
    +    pub height: u16,
    +}
    +```
    +
    +it is **_not_** possible to initialize a `Config` in a different *crate B* (13):
    +
    +```rust
    +let config = Config { width: 640, height: 480 };
    +```
    +
    +This is forbidden when `#[non_exhaustive]` is attached because the purpose of
    +the attribute is to permit adding fields to `Config` without causing a
    +breaking change. However, the RFC goes on to note that you can pattern match
    +if you allow for the possibility of having fields be ignored with `..` (14):
    +
    +```rust
    +let Config { width, height, .. } = config;
    +```
    +
    +Because this RFC gives a way to have default field values, you can now simply
    +invert the pattern expression and initialize a `Config` like so (15):
    +
    +```rust
    +let config = Config { width, height, .. };
    +```

    Honestly, I think it would be useful to preserve the property that Struct { field: value, .. } as an expression (the proposed syntax) is equivalent to Struct { field: value, ..Default::default() }, and as such, these examples would only work if these structs derived or manually implemented Default.

    That should cover the API concerns, although it would make Default become a lang item, which I am personally fine with but I am not everyone, so, that would be a downside to this approach.

    If it doesn't interact with Default at all, I agree that it shouldn't allow this, since it does break APIs.

    orangecms orangecms commented on Aug 24, 2024 12:33 UTC
    Contributor

    This is excellent!
    I'm sometimes dealing with binary data structures, mostly vendor specific headers, and so far felt like defaults / fixed values caused quite some duplication. This approach reduces that, thank you! 👏

    estebank estebank commented on Aug 28, 2024 22:15 UTC
    Author

    I believe I've addressed most of the comments (and have collapsed conversations to make way for new ones). Feel free to add additional comments for anything that might be missing.

    As a recurring thing: I believe we need to target the minimal version of this feature that does not block future expansion.

    Whether building Config { .. } where Config has private fields is allowed one that needs to be defined somewhat one way or another. If it is allowed by default, then the interaction with #[non_exhaustive] needs to be defined. If it is allowed as opt-in, then the conversation can be delayed.

    I strongly believe that allowing non-const default values, at least at start, is not a good idea, while it can always be extended later. I'm also looking forward for ~const Default to be a thing in the std.

    Whether enum struct variant support should be included in the first version or not is one I flip-flop on myself: currently we can only #[default] unit variants, so the either we add the literal Enum::Variant { .. } support without expanded #[derive(Default)] support, extend the #[derive(Default)]/#[default] support to work only if all fields are defaulted, extend the support to work with Default::default() when possible with imperfect derives, or we withhold support for Enum::Variant { .. } until this gets resolved. None of the options are ideal, as they will all end up with a special case for general rules, one way or another.

    I have a pretty functional implementation of the feature (with some of the above questions answered in the way that made it easiest to implement quickly: only const expressions are allowed, private fields can't be constructed and with no opt-in, enum variants can be defaulted and built) in https://github.com/rust-lang/rust/pull/129514, and it is already more functional than I imagined it would be.

    jhpratt jhpratt commented on Aug 29, 2024 05:06 UTC
    Contributor

    Obligatory link to pre-RFC from December 2021, which was itself taken (in part) from a draft RFC from December 2018.

    There was a fair amount of discussion for the former, with a smaller amount on the latter. Naturally quite a bit has changed in the ensuing six years, but the discussions remain relevant given the drafting history here.

    matthieu-m matthieu-m commented on Aug 29, 2024 17:57 UTC
    Contributor

    I'm afraid the section on Imperfect derives is too optimistic.

    I suppose it makes sense _intuitively_ that None doesn't require T: Default, but what about an _arbitrary expression_?

    This RFC mentions #[serde(default)] as something that could eventually be removed (yes!), however #[serde(default)] supports much more than literals & identifiers: it supports arbitrary function calls.

    And arbitrary function calls may (1) infer their generic arguments, so they are invisible at the syntax level and (2) and may impose requirements on those generic arguments.

    For a "regular" use of this feature, the fact that arbitrary invisible requirements exist is a non-issue:

    - When using Foo { .. } the requirements from the context are "inherited" automatically.
    - When a requirement is missing in a manual context, it can simply be added.

    However I'm afraid for derive it's a tad more difficult...

    To make things concrete:

    pub struct NonEmptyVec<T> { ... }
    
    impl<T> NonEmptyVec<T> {
        pub const fn default_singleton() -> NonEmptyVec<T> 
        where
            T: ~const Default,
        { ... }
    }
    
    #[derive(Default)]
    pub struct MyThing<T> {
        foos: Vec<T> = Vec::new(),
        bars: NonEmptyVec<T> = NonEmptyVec::default_singleton(),
    }
    

    I don't think that #[derive(Default)] can assume that Vec::new() and NonEmptyVec::default_singleton() DO NOT require T: Default. And in fact, the latter does.

    FlixCoder FlixCoder commented on Aug 29, 2024 19:17 UTC
    Contributor

    At first glance, I thought this is a bad idea: we suddenly have the possibility to specify field defaults, that are different from the the Default trait implementation. This can be quite confusing. So MyStruct { .. } != MyStruct { ..Default::default() }.

    But there is a really big benefit: being able to require mandatory fields, while still providing defaults to the other fields. This removes a LOT of derived builders with their own duplicate default definition for actually just data records without any logic. So I ended up with huge compile time costs and less ergonomy, because builders check existence of required fields at runtime and return errors (unless using compile time builders, with even more compile time cost).

    So overall I really like this proposal!

    scottmcm scottmcm commented on Sep 11, 2024 17:55 UTC
    Contributor

    I've wanted something like this for ages. I took a fresh read through here after the updates, and other than what looks like a vestigial section, it looks good to go to me! Let's see what the rest of the team thinks.

    @rfcbot fcp merge

    rfcbot rfcbot commented on Sep 11, 2024 17:55 UTC
    Contributor

    Team member @scottmcm has proposed to merge this. The next step is review by the rest of the tagged team members:

    [ ] @joshtriplett
    [x] @nikomatsakis
    [x] @pnkfelix
    [x] @scottmcm
    [x] @tmandry
    [x] @traviscross

    No concerns currently listed.

    Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!

    cc @rust-lang/lang-advisors: FCP proposed for lang, please feel free to register concerns.
    See this document for info about what commands tagged team members can give me.

    tmandry tmandry commented on Sep 19, 2024 00:44 UTC
    Contributor

    Overall I'm a huge fan of this RFC. I would like to see more on the treatment of #[non_exhaustive] and private fields, so let me provide a use case that can act as a bit of motivation.

    I don't think we can realistically "punt" here: Disallowing use of Foo { .. } outside a module is very important for typestate patterns, and therefore any way of doing that will need to continue being supported in the future.

    Our use case: The repr(C) options struct

    Let's say we want to have a struct like the following.

    #[repr(C)]
    #[non_exhaustive]
    pub struct zx_packet_page_request_t {
        pub command: u16,
        pub flags: u16 = 0,
        reserved0: u32 = 0,
        pub offset: u64,
        pub length: u64,
        reserved1: u64 = 0,
    }
    

    Here we have a repr(C) struct whose layout cannot change, but which might add fields that use up the space in reserved0 and reserved1 in the future. We are constrained in the future evolution that setting the bytes that correspond to reserved0 and reserved1 to zero must retain the same meaning as today.

    It would not be appropriate to specify defaults for all fields, but we can specify defaults for some of them. The struct is #[non_exhaustive] because we might add more field names in the future, and any places that list all field names will need to account for this with ... It also has private fields because the names reserved0 and reserved1 might disappear (or change types) in the future.

    We would like users to be able to specify a value of this struct like this: zx_packet_page_request_t { command: ZX_PAGER_VMO_READ, offset: 0, length: 128, .. }. This would allow for evolving the struct without introducing any source breakage.

    Option 0: Don't support .. on structs with #[non_exhaustive] or private fields

    As the RFC states today, we can choose not to support this (outside the defining module).

    If we stopped here it would be a disappointing outcome, but this is forward-compatible with several of the other options here.

    Option 1: Opt-in for #[non_exhaustive], always allow for private fields

    For reasons brought up by @scottmcm, we probably can't allow it directly for #[non_exhaustive], so we would need a way to opt in anyway with a #[defaultable] attribute or similar. But we could choose to always allow .. initialization for private fields.

    The main disadvantage is that users who want to use private fields to prevent construction would not be able to if those private fields are defaulted. They would have to leave off the default or use bare #[non_exhaustive] (without the opt in). The first is an ergonomic loss (needing to list _private: () in each initialization). The second is better and works today, but I would argue it makes the intent less obvious when reading the code.

    This option is not backwards compatible with Option 0 in my view, because we should never silently allow structs which where unconstructible outside a module to suddenly become constructible.

    Option 2: Opt-in for #[non_exhaustive], but private fields are unsupported

    We could say that the use of private fields in this instance would be nice, but ultimately we just don't want to accept that .. can be used to initialize private fields; it would be too out of line with privacy as it is today in Rust. Any use of the "defaultable" opt-in that also had private fields would result in a compiler error.

    This restriction mainly impacts the repr(C) use case, which could still be supported by exposing a second builder struct that contained only the public subset of fields. This builder struct would be a defaultable #[non_exhaustive] struct, with a .build() method that creates the actual struct, including setting the field names we don't want to expose. This would continue to be an ergonomic win for users, who get to forward-compatibly use the struct initializer syntax with .., but not for the crate authors who need to create such builders (or use a macro).

    This option is backwards compatible with Option 0.

    Option 3: Opt-in for both #[non_exhaustive] and private fields

    Make a #[defaultable] attribute that opts into allowing .. initialization outside the defining module for _both_#[non_exhaustive] and private fields. Any non-defaulted private fields would be a compiler error, and adding public non-defaulted fields would be a semver breaking change.

    This option is backwards compatible with both Option 0 and Option 2.

    Analysis

    We have to decide whether to accept or reject Option 1 as part of this RFC. Options 2 and 3 are backward compatible with Option 0, so we could choose to stick with Option 0 as written and reject Option 1.

    Recommendation

    After writing all this out, I find myself in favor of Options 2 and 3. I think a #[defaultable] attribute should apply equally to private fields and #[non_exhaustive], since those are in many ways equivalent today. It should also error in cases where a struct is not actually defaultable outside the defining module.

    Since Option 0 is forward compatible with these I'm okay with the normative RFC text as written, but I would like to see some discussion of this in the future possibilities section if possible (feel free to copy this comment).

    tmandry tmandry commented on Sep 19, 2024 01:31 UTC
    Contributor

    @rfcbot reviewed

    I'm okay with const-only initializers to start because we can always choose to relax this restriction later,[^relax] and there are several mitigating possibilities (described below) that can make this feature work better with Default. The only thing that would make me hesitate to accept this RFC is if we decided to do _none_ of these, which I think is unlikely.

    [^relax]: I have to keep reminding myself why this is, so this is a note to my future self. If we do relax the const restriction we will allow more types to be used with .. initializers, but only in non-const contexts. This won't break any existing usages in const contexts, of course, since those types were always const to begin with. For struct authors it does present the possibility of accidentally breaking uses of .. by adding non-const initializer exprs, which we could mitigate with a lint or by requiring more explicit syntax like braces. \
    \
    In the cases where .. will invoke #[derive(Default)], we would of course have to allow it without a lint on the struct. This is fine; there's a slight chance of semver breakage in going from all = constexpr to #[derive(Default)] but that could be easily fixed with #[derive(const Default)]. We can allow using .. which invokes Default in non-const contexts, and optionally lint on uses which invoke a manual non-const impl, since as the argument goes, people won't expect Foo { .. } to have side effects.

    There are several future possibilities I would like to see mentioned in the RFC. But this is a non-normative section and I don't want to block this RFC from going forward.

  • Options for making #[non_exhaustive] and/or private fields work, as I laid out in the above comment

  • - Looking at the current sections, there's not much I said that isn't allowed for there, though I prefer to restrict the set of options somewhat and consider the two features together. I also like the motivating use case I provided, but it's admittedly one I'm close to.
  • Working with #[derive(const Default)], as elaborated here.

  • - And possibly any struct with an impl const Default for T, though that feels a bit more magic.
    - Alternatively, if we don't make these work together but do have const Default and RFC 3591, specifying a default value for every field can be done more concisely as field: Ty = default().
    - This is arguably an elaboration of the "Default implementations are not currently ~const" point.
  • A "splat operator" for using fields as named values in function signatures, as described here.
  • programmerjake programmerjake commented on Sep 19, 2024 03:07 UTC
    Contributor

    https://github.com/rust-lang/rfcs/pull/3681#issuecomment-2359685895

    After writing all this out, I find myself in favor of Options 2 and 3.

    I agree, though tbh I prefer Option 3 over Option 2.

    scottmcm scottmcm commented on Sep 19, 2024 06:00 UTC
    Contributor

    @tmandry I agree I'd like to move to something like option 3 (in the future, not here), though I've been spelling it differently in terms of how to opt-in, since we've talked about other targeted opt-outs of other parts of non_exhaustive too.

    RalfJung RalfJung commented on Sep 19, 2024 06:25 UTC
    Contributor

    For reasons brought up by @scottmcm, we probably can't allow it directly for #[non_exhaustive]

    What are those reasons? A link would have been nice. :)

    At first sight, it is not clear to me why "all private fields have a default" is not sufficient to allow Foo { fields, .. }, assuming all non-default fields are listed. #[non_exhaustive] would then promise that all fields added in the future have a default. Or is it that promise that the opt-in is about?

    scottmcm scottmcm commented on Sep 19, 2024 06:28 UTC
    Contributor
    traviscross traviscross commented on Sep 24, 2024 04:32 UTC
    Contributor

    @rustbot labels +I-lang-nominated

    I too want something like this. But I'm not sure yet whether I want exactly this. Mostly I have some reservations about the inequivalence between let x = Foo { .. } and let x = Foo { ..Foo::default() }, the implications of that inequivalence on how people would structure code, and how and whether we could ever close that gap.

    Maybe it'd help to see some experimentation here. I'd be interested in trying this out on nightly under an experimental feature flag. I see that there's a draft PR over in:

  • https://github.com/rust-lang/rust/pull/129514
  • Or maybe it'd be enough to talk this through. I've proposed:

  • https://github.com/rust-lang/lang-team/issues/291
  • estebank estebank commented on Sep 24, 2024 14:33 UTC
    Author

    I have some reservations about the inequivalence between let x = Foo { .. } and let x = Foo { ..Foo::default() }, the implications of that inequivalence on how people would structure code, and how and whether we could ever close that gap.

    As part of stabilization I would want to have a lint warning against manual impl Default for Foo if there are default fields, which should mitigate the potential for divergence in behavior. I would expect that default fields will be used either to preclude the need of manual impl or for types with mandatory fields, where Default isn't suitable. I struggle to think of use-cases that don't fall in either of those buckets.

    scottmcm scottmcm commented on Sep 24, 2024 22:53 UTC
    Contributor

    +1 to linting -- I think we can also do things like "hey, you put defaults for all the fields, so you should probably derive(Default) too" (at least in clippy/ra, if maybe not in rustc)

    traviscross traviscross commented on Sep 24, 2024 23:49 UTC
    Contributor

    Perhaps the most space saving would be to prevent any impl of Default (even derived) for a type with default fields but not defaults for all fields, and then to permit only (and suggest) a derived Default impl for types with defaults for all fields.

    CraftSpider CraftSpider commented on Sep 25, 2024 02:04 UTC
    Contributor

    That first part sounds very annoying, as a user - I often manually override Default just to change one or two fields, but now I have to add = 0 (or an even more complex expression) to every other field anyways. Which is noisy and, at least to me, feels like a very artificial restriction for a situation that has an incredibly obvious expected behavior. I'd expect at least deriving to work.

    traviscross traviscross commented on Sep 25, 2024 05:12 UTC
    Contributor

    ...but now I have to add = 0... to every other field anyways. Which is noisy...

    The trouble is that if you don't add those = 0s to all fields, then the Foo { .. } syntax in this RFC doesn't work, so regardless of any hypothetical restrictions, this RFC would push people to do that.

    That's one of the things we're trying to sort out.

    scottmcm scottmcm commented on Sep 26, 2024 02:41 UTC
    Contributor

    Spitballing: what if Foo { .. } default-initialized even the things that don't have defaults? (Basically, assuming we have a const Default of some sort, it puts in Foo { a: const { Default::default() }, … }.)

    I guess the problem that has is that you can just put Options { .. } even if there's a "required" field, and there'd be nothing to nudge you back to actually setting those fields. (Because if you got a lint if they didn't have defaults then the library author would still need to add the = 0s.)

    Unsure how I feel about it. Certainly seems kinda weird.

    On the other hand, if you want the compiler to tell you what fields exist, you could just write Options {} instead and it'll tell you about stuff. And auto-inserting zeroes is not really any worse than if someone just writes in those values themselves, so the code needs to check for those values anyway.

    And there's always the option of doing it with some opt-in subtrait of Default instead, which would be a way for types to say that while they're Default as a convenience, they're not really meaningfully default. One version of that could even be "well it's only Option that implements it", so that you don't need to = None; manually on those. (I guess also PhantomData and some others like that too, but a very restricted set that wouldn't include &str and such.)

    traviscross traviscross commented on Sep 26, 2024 03:24 UTC
    Contributor

    I guess the problem that has is that you can just put Options { .. } even if there's a "required" field

    In that world we could have some way -- an attribute, syntax, something -- to indicate that a field is required to be set even if its type implements Default. That is, rather than that being implicit by it not having = 0, we could explicitly indicate requiredness.

    mhnap mhnap commented on Sep 26, 2024 09:35 UTC
    Contributor

    The trouble is that if you don't add those = 0s to all fields, then the Foo { .. } syntax in this RFC doesn't work, so regardless of any hypothetical restrictions, this RFC would push people to do that.

    As a user, I find this to be expected behavior. It feels logical that Foo { .. } syntax can work only if there are provided default values for all fields. At the same time, Default can be used as always. So, something like this would be possible:

    #[derive(Default)]
    pub struct Foo {
        pub alpha: &'static str,
        pub beta: bool,
        pub gamma: i32 = 42,
    }
    
    // This impl would be generated from derive
    impl Default for Foo {
        fn default() -> Self {
            Self { alpha: Default::default(), beta: Default::default(), gamma: 42 }
            // or
            Self { alpha: Default::default(), beta: Default::default(), .. } // gamma: 42
        }
    }
    
    let f = Foo { .. }; // rejected
    let f = Foo { alpha: "", beta: false, .. }; // ok, gamma: 42
    let f = Foo { ..Default::default() }; // ok
    let f = Foo::default(); // ok
    

    tmandry tmandry commented on Sep 26, 2024 21:32 UTC
    Contributor

    The trouble is that if you don't add those = 0s to all fields, then the Foo { .. } syntax in this RFC doesn't work, so regardless of any hypothetical restrictions, this RFC would push people to do that.

    > That's one of the things we're trying to sort out.

    I talk about this in my above comment too. I see a couple ways of unifying them that are backward-compatible with the RFC as written:

  • #[derive(const Default)] on the struct means that all fields are defaulted without having to write = 0 everywhere.

  • Relax the const restriction, and make Struct { .. } do the same thing as Struct { ..Default::default() } (modulo field privacy, which is an aspect of FRU I do not want to retain)
  • I think where I land is:

  • Use #[derive(const Default)] if you want the obvious, unified thing to work and you're default- and const-constructible.

  • Otherwise, use = default() on the defaulted fields (after https://github.com/rust-lang/rfcs/pull/3591).

  • Consider non-const defaults as an independent extension.

  • Consider the .. = default() extension I mention below independently.
  • tmandry tmandry commented on Sep 26, 2024 21:33 UTC
    Contributor

    Spitballing: what if Foo { .. } default-initialized even the things that _don't_ have defaults? (Basically, assuming we have a const Default of some sort, it puts in Foo { a: const { Default::default() }, … }.)

    I don't think I would want it to invoke the default constructor of the _field_ type. What we are trying to unify here is Struct { .. } with Struct::default(). A struct without a default impl might lack that impl for a reason: While the individual field types might all be defaultable, it is entirely possible for their combined defaults to be an incoherent value of the _struct_.

    In that world we could have some way -- an attribute, syntax, something -- to indicate that a field is required to be set even if its type implements Default. That is, rather than that being implicit by it not having = 0, we could explicitly indicate requiredness.

    That is an interesting idea! But again, I don't think we should make all structs implicitly default-constructible just because their fields are all default-constructible. So to have an opt-out, we would also have to have an opt-in. Maybe something like:

    struct Foo {
      x: i32,
      #[required] y: String,
      .. = Default::default()
    }
    

    traviscross traviscross commented on Sep 26, 2024 23:21 UTC
    Contributor

    I see a couple ways of unifying them that are backward-compatible with the RFC as written:

    ...

    Relax the const restriction, and make Struct { .. } do the same thing as Struct { ..Default::default() } (modulo field privacy, which is an aspect of FRU I do not want to retain)

    Unfortunately, I don't think this is backward-compatible.[^1] Under the RFC, S { .. } and S::default() can return arbitrarily different things. That's why I mused:

    Perhaps the most space saving would be to prevent any impl of Default (even derived) for a type with default fields but not defaults for all fields, and then to permit only (and suggest) a derived Default impl for types with defaults for all fields.

    ...as that restriction would save this space in both directions by preventing S::default() from working when S { .. } does not and ensuring that S { .. } and S::default() return the same value when both work.

    [^1]: I read the footnote in the comment above about why that should be true, but I can't reconcile it.

    traviscross traviscross commented on Sep 26, 2024 23:41 UTC
    Contributor

    Regarding the outstanding analysis that, @tmandry, you did here on the interaction of this with non_exhaustive and field privacy... I might prefer to see us at least try to solve this along with the rest of the design and while we have this loaded into cache. (Landing this in nightly under an experimental feature flag might help here too.)

    Perhaps it'd also be useful for the RFC to integrate a description of the use case you mention and ensure it captures the substance of your analysis, though I note that it does already have its own extensive analysis.

    tmandry tmandry commented on Sep 27, 2024 00:56 UTC
    Contributor

    Unfortunately, I don't think this is backward-compatible.1 Under the RFC, S { .. } and S::default() can return arbitrarily different things.

    I wasn't trying to solve that, so in my proposal a: i32 = 17 would take precedence over impl Default on the same struct when S { .. } is used. The Default impl would only be used for fields that have no explicit default.

    I agree it's a bit messy to let these diverge, but I think a lint is an acceptable way of addressing that, possibly going so far as to deny-by-default when there are no valid use cases left.

    While it would be nice not to allow divergence at all, I wouldn't hold back a substantial part of the benefit of this RFC for that.

    lolbinarycat lolbinarycat commented on Sep 27, 2024 23:04 UTC
    Contributor

    why not just forbid manually implementing Default on structs with field defaults? that gets around the nasty ..Default::default() parity issue, and is a restriction that can be relaxed in the future.

    also, an advantage the rfc does not list is that these defaults will presumably show up in rustdoc-generated documentation, while a manual implementation of Default will not, often requiring repetition of those defaults in doc comments, and those comments are liable to get out of sync with the actual default.

    lolbinarycat lolbinarycat commented on Sep 27, 2024 23:10 UTC
    Contributor

    I wasn't trying to solve that, so in my proposal a: i32 = 17 would take precedence over impl Default on the same struct when S { .. } is used. The Default impl would only be used for fields that have no explicit default.

    what happens in this case:

    struct Weird {
      a: u8 = 1,
      b: u8,
    }
    
    impl Default for Weird {
      fn default() -> Self {
        Self {
          a: 2,
          b: 3,
        }
      }
    }
    

    what does dbg!(Weird{ .. }) print? does it use the u8 Default or the Weird one?

    skogseth skogseth commented on Sep 28, 2024 14:42 UTC
    Contributor

    > I wasn't trying to solve that, so in my proposal a: i32 = 17 would take precedence over impl Default on the same struct when S { .. } is used. The Default impl would only be used for fields that have no explicit default.

    > what happens in this case:

    >
    > struct Weird {
    >   a: u8 = 1,
    >   b: u8,
    > }
    > 
    > impl Default for Weird {
    >   fn default() -> Self {
    >     Self {
    >       a: 2,
    >       b: 3,
    >     }
    >   }
    > }
    > 

    > what does dbg!(Weird{ .. }) print? does it use the u8 Default or the Weird one?

    ~~This would give a compilation error saying that you need to specify the value for b, as it doesn't have a default field value specified.~~ Nevermind, I think I misunderstood what you were responding to.

    Assignees
    estebank estebank
    Labels
    risk: low confidence: 89.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 43.0% (MEDIUM) · Higher = larger blast radius
    43.0%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.2% · Lower = rushed or shallow review
    89.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.7% · Safe to merge
    4.7%
    Repository