Partial Moves And Struct Update Syntax
Derive struct variants with the ..base update syntax, then lift individual fields out with partial moves while untouched fields stay readable in place.
Code
#[derive(Debug)]
struct ServerConfig {
host: String,
port: u16,
tags: Vec<String>,
}
fn main() {
let cfg = ServerConfig {
host: String::from("api.example.com"),
port: 8080,
tags: vec!["edge".into(), "http".into()],
};
// 结构体更新语法:显式字段覆盖,其余字段从 base 逐个移出(base 随即失效)
let tls = ServerConfig { port: 443, tags: vec!["tls".into()], ..cfg };
println!("tls variant: {tls:?}");
// println!("{:?}", cfg); // ← 编译错误:cfg 的字段已被全部移出
// 部分移动(partial move):只移走一个字段,其余字段原地继续可用
let cfg2 = ServerConfig {
host: String::from("backup.example.com"),
port: 9000,
tags: vec!["retry".into()],
};
let tags = cfg2.tags;
println!("moved tags: {tags:?}");
println!("cfg2 host/port still usable: {} {}", cfg2.host, cfg2.port);
}How the snippet works
Count the function main as the entire surface area of Partial Moves And Struct Update Syntax.
Using it
Running the file prints labeled results such as tls variant:, moved tags:, cfg2 host/port still usable: — each operation’s effect is visible in the output.
Key statements
let tls = ServerConfig { port: 443, tags: vec!["tls".into()], ..cfg };
let tags = cfg2.tags;
Interactive Tools for This Topic
Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Partial Moves And Struct Update Syntax print when run?
- Invoke the file as-is — the `tls variant:`, `moved tags:`, `cfg2 host/port still usable:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.