Skip to content

[第2章] 2.3变量与绑定-2.3.3 所有权与引用 #342

@ltcz997

Description

@ltcz997

页码与行数

代码清单2-5:所有权转移


文本或排版错误

暂无


代码错误

fn main(){
    let place1 = "hello";
    let place2 = "hello".to_string();
    let other = place1;
    println!("{}", other);
    println!("{}", place1);

    let other = place2;
    println!("{}", other);
}

Rust版本

rustc -V
rustc 1.89.0 (29483883e 2025-08-04)

错误信息

实际代码不会在 println!("{:?}", other); 处直接报错,因为 let other = place2; 是重新绑定 other(变量遮蔽),移动后 other 是有效的,真正失效的是 place2。如果之后使用 place2 才会报错。
let place1 = "hello"; // place1: &str
let place2 = "hello".to_string(); // place2: String
let other = place1; // place1 的值被复制(或说绑定共享)
println!("{:?}", other); // 正常打印
let other = place2; // place2 的值被移动到 other
println!("{:?}", other); // 正常打印,但 place2 已失效
// println!("{:?}", place2); // 这才会报错:value used here after move

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions