Pre-RFC: syntactic sugar for initializing fields with the same expression

i've see a few proposals for making it easier to work with optional fields and partial initialization, so here's my idea.

it's mainly inspired by the shorthand for initializing arrays, and the existing .. struct syntax.

here's a example of what this might look like:

struct User {
  first_name: Option<String>,
  last_name: Option<String>,
  post_count: u64,
  id: Uuid,
}

impl User {
  fn new() -> Self {
    User { id: Uuid::new_random(), ..: Default::default() }
  }
}

the ..: syntax[1] would initialize all fields not previously named with the given value, in this case Default::default. if the expression is not valid for all fields, it will give a typecheck error.

this would be useful in a lot of cases, not just for when you want a partial default, but also if you want to expose the all-default case in some sort of empty() method, but provide a more useful value for the actual Default trait impl. you could even use it for easily initializing a pure diagonal vector, handy for things like scaling a 3d model evenly across all axes.

like .., this syntax would not be useable on structs with fields that are not in scope[2]


  1. this might be too similar to the .. syntax but i can't think of anything better ↩︎

  2. as well as non_exhaustive structs that are defined in other crates ↩︎

Without a potential syntax which is more distinct than ..:, it's a very hard sell. Before any work into something like this, I'd much prefer following through the proposal to have per-field defaults available, which addresses much the same use cases.

That, plus there's some discussion on whether FRU should be changed from moving from the rest place to instead moving into the rest place.