You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 07:15:39