rust / intermediate
Snippet
Struct Update Syntax with Default
Rust's struct update syntax using `..` allows you to create a new struct instance while copying most fields from an existing one. Combined with the `Default` derive macro, it enables efficient configuration patterns where you start with a base configuration and override only specific fields.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#[derive(Default, Debug)]struct Config {host: String,port: u16,timeout: u64,}fn main() {let base = Config {host: String::from("localhost"),port: 8080,timeout: 30,};let override_config = Config {timeout: 60,..base};println!("{:?}", override_config);}
Breakdown
1
#[derive(Default, Debug)]
Derive macro that implements Default trait for zero-value initialization and Debug for printing
2
struct Config { host: String, port: u16, timeout: u64 }
Struct definition with three fields: host (String), port (u16), and timeout (u64)
3
let base = Config { host: String::from("localhost"), port: 8080, timeout: 30 }
Create a base configuration instance with default values for all fields
4
let override_config = Config { timeout: 60, ..base }
Create a new config by overriding only timeout, copying host and port from base
5
println!("{:?}", override_config)
Print the override_config using Debug formatting: Config { host: "localhost", port: 8080, timeout: 60 }