Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ".." syntax inside a struct literal in Rust?

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?

like image 514
Evan Rose Avatar asked Jan 22 '18 19:01

Evan Rose


People also ask

How do you define a struct in Rust?

To define a struct, we enter the keyword struct and name the entire struct. A struct's name should describe the significance of the pieces of data being grouped together. Then, inside curly brackets, we define the names and types of the pieces of data, which we call fields.

Can structs have functions Rust?

Rust uses a feature called traits, which define a bundle of functions for structs to implement. One benefit of traits is you can use them for typing. You can create functions that can be used by any structs that implement the same trait.

How do you define a struct?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

How do you pass a struct to a function in Rust?

We can pass a struct to a function by specifying the struct name as the type in the parameter list. We can return a struct from a function by specifying the struct name as the return type. We can define functions that are specific to a struct, called methods, that can only be used by instances of that struct.


1 Answers

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.

like image 110
Shepmaster Avatar answered Oct 19 '22 10:10

Shepmaster