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]