关于Rust中引用克隆与解引用克隆的差异及克隆行为的疑问
Rust中引用克隆与解引用克隆的差异及克隆行为的疑问
最近我在琢磨Rust里克隆引用和解引用克隆的区别,写了段代码测试:
#[derive(Clone, Debug)] #[allow(unused)] struct Settings { volume: u16, } fn main() { let settings = &Settings { volume: 10 }; let a = (*settings).clone(); // (1) let b = settings.clone(); // (2) println!("address of 'settings' point to: {:p}", settings); println!("address of 'a': {:p}", &a); println!("address of 'b': {:p}", &b); }
运行之后的输出是:
address of 'settings' point to: 0x55e784c480a8 address of 'a': 0x7ffebad638b4 address of 'b': 0x7ffebad638b6
我发现所有变量的地址都不一样,之后去翻了标准库中Clone trait的文档,里面是这么说的:
Calling clone always produces a new value. However, for types that are references to other data (such as smart pointers or references), the new value may still point to the same underlying data, rather than duplicating it. See Clone::clone for more details.
这就让我有点疑惑了——那是不是说如果我们克隆的是引用类型,就不会对目标变量进行深克隆呢?
内容来源于stack exchange
相关产品推荐
相关产品推荐

