ZhangHanDong / tao-of-rust-codes

《Rust编程之道》随书源码
https://ruststudy.github.io/tao_of_rust_docs/tao_of_rust/
MIT License
1.18k stars 170 forks source link

第二章2.3.3 关于所有权转移代码示例可能有误 #328

Closed jasonzhouy closed 2 years ago

jasonzhouy commented 2 years ago

页码与行数


文本或排版错误

在rust1.5.7版本中运行并没有出现所有权转移的error,我认为是不是内容撰写时有误?此处第二个println!()应该想通过输出的是place1或者place2来展示所有权转移,而不是输出other?


代码错误

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

Rust版本

$ rustc -V
rustc 1.57.0 (f1edd0429 2021-11-29)
ZhangHanDong commented 2 years ago

@jasonzhouy 感谢反馈。这个示例已经勘误过了。

uran0sH commented 2 years ago

这个代码示例下面的解释有点疑惑,place1会将内存地址转移给other,这里的内存地址指的是啥?

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

从上面的输出可以看出place1和other是不一样的地址

ZhangHanDong commented 2 years ago

@uran0sH 感谢反馈。

“place1会将内存地址转移给other” 是指 place1 会移动,内存地址为变为 other 的。这里主要是想说明转移的是内存地址,可能文字描述有歧义吧,并不是指内存地址的值转移给other。