由于 Rust 中只能有一个所有者,这是否意味着浅拷贝是不可能的?

Since there can only be one owner in Rust, does that mean shallow copies aren't possible?

我正在尝试了解所有权模型。由于 Rust 中只能有一个所有者,这是否意味着浅拷贝是不可能的?有没有类似于浅拷贝的东西?我猜你可以用引用做一些事情,但这会迫使你使用不同的类型吗?

Rust 使用不同的类型来表示不同程度的所有权(单一所有权、共享所有权或借用)。进行浅表复制意味着副本将 与原始数据共享 一些数据。这意味着我们必须使用支持共享的类型

制作浅拷贝的一种方法是复制共享引用。例如,考虑这个程序:

#[derive(Clone, Debug)]
struct Greetings<'a> {
    hello: &'a str,
    goodbye: &'a str,
}

fn main() {
    let greetings = Greetings {
        hello: "Hello!",
        goodbye: "Goodbye!",
    };
    let new_greetings = greetings.clone();
    println!("{:?}", new_greetings);
}

当我们克隆 greetings 时,我们实际上并没有克隆字符串;我们只有 "clone" 引用(只是指针)。编译器在 Greetings 上使用生命周期参数来确保 Greetings 的实例不会超过存储在其中的字符串。

制作浅拷贝的另一种方法是将拥有的对象存储在 RcArc 智能指针中并克隆该指针。例如:

use std::rc::Rc;

#[derive(Clone, Debug)]
struct Greetings {
    hello: Rc<String>,
    goodbye: Rc<String>,
}

fn main() {
    let greetings = Greetings {
        hello: Rc::new("Hello!".into()),
        goodbye: Rc::new("Goodbye!".into()),
    };
    let new_greetings = greetings.clone();
    println!("{:?}", new_greetings);
}

当我们克隆 greetings 时,Rc 对象也被克隆。当一个Rc被克隆时,引用计数器增加,但是Rc管理的对象没有被克隆;相反,原始和克隆的 Rc 对象都引用相同的 String 对象。