Rust struct update syntax Link to heading
I recently came across some syntax in Rust that I was not familiar with from other languages, so I wanted to make a note of this syntax: struct update syntax with ..
// Define a struct with four fields
struct Point {
x: i32,
y: i32,
z: i32,
w: i32,
}
// Create an instance of Point with default values
let origin = Point { x: 0, y: 0, z: 0, w: 0 };
// Create a new instance of Point that has the same values as origin
// except for the x field, which is 1
let point = Point { x: 1, ..origin };
// Print the values of point
println!("point.x = {}, point.y = {}, point.z = {}, point.w = {}", point.x, point.y, point.z, point.w);
It turns out that this syntax is not new to Rust — other languages, such as Haskell, Elm, TypeScript, and JavaScript has a similar feature. I am not too familiar with any of those languages, so it was a first time for me.