小编Akk*_*kki的帖子

Rust 结构更新语法而不获取所有权

#[derive(Debug)]
struct Car {
    company: String,
    model: String,
    cost: i32
}

fn main() {
    let car1 = Car {
        company: String::from("Ford"),
        model: String::from("123xyz"),
        cost: 50000
    };
    let car2 = Car {
        model: String::from("987pqr"),
        cost: 47000,
        ..car1
    };
    println!("{:#?}", car2);
    println!("{:#?}", car1.company);
}
Run Code Online (Sandbox Code Playgroud)

这里编译器正确地告诉我:

println!("{:#?}", car1.company);
                  ^^^^^^^^^^^^ value borrowed here after move
move occurs because `car1.company` has type `String`, which does not implement the `Copy` trait
Run Code Online (Sandbox Code Playgroud)

我知道 String 实例位于堆上,这就是它无法复制的原因,所有权已移至car2.company. 我可以通过这样的方式解决这个用例:

println!("{:#?}", car1.company);
                  ^^^^^^^^^^^^ value borrowed here after move
move …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
829
查看次数

标签 统计

rust ×1