24

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?

1

1 Answer 1

32

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.

5
  • I've also seen initialization like this let SomeOptions { foo: 42 .. } = SomeOptions::default(); which seems similar. Does anyone know what it does?
    – Shabgard
    Nov 23, 2020 at 10:21
  • 2
    @Shabgard you have not seen that in real Rust code because it's invalid Rust syntax. If you meant let SomeOptions { foo, .. } =, then Ignoring Remaining Parts of a Value with ..
    – Shepmaster
    Nov 23, 2020 at 13:11
  • Thank you. No, I don't think it's the case that you mentioned but it was also educating for me. This piece of code is the exact instance of the usage that I had in mind.
    – Shabgard
    Nov 23, 2020 at 14:18
  • @Shabgard that's exactly the syntax that I used in my comment; why do you think it's different?
    – Shepmaster
    Nov 23, 2020 at 14:41
  • Oh, I got confused because of the link you sent was pointing to this section "Ignoring Remaining Parts of a Value with .." which was used inside a match block. But now that I studied the whole page it seems to be the case of Destructuring Structs. Now I understand it. Very helpful page anyway!
    – Shabgard
    Nov 23, 2020 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.