Issue
From the std::default::Default
docs:
#[derive(Default)]
struct SomeOptions {
foo: i32,
bar: f32,
}
fn main() {
let options = SomeOptions { foo: 42, ..Default::default() };
}
What is the ..
prefix doing to the returned value of Default::default()
and why is it necessary here? It almost seems like it's acting as a spread operator, but I'm not sure. I understand what ..Default::default()
is doing -- filling in the remaining struct parameters with the default values of SomeOptions
, but not how ..
works. What is the name of this operator?
Solution
This is the struct update syntax. It is "needed" only to have a succinct way of moving / copying all of the members of a struct to a new one, potentially with some small modifications.
The "long" way of writing this would be:
let a = SomeOptions::default();
let options = SomeOptions { foo: 42, bar: a.bar };
You could indeed think of it similar to the JavaScript "spread" operator, but Rust's nuances of ownership and strong typing still come into play, so it's not as widely used. For example, you can't use this syntax to go between values of different types.
Answered By - Shepmaster Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.