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.

RustData Integrity

Code

rustsnippet
29 lines
#[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

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.