有了这code on the rust playground个:

fn main() {
    let a = &[1, 2, 3];
    
    let mut o = a.to_owned();
    let mut c = a.clone();
    let mut d = *a;
    
    o[0] = 7;
    c[0] = 8;
    d[0] = 9;
    
    println!("o: {:?}", o);
    println!("c: {:?}", c);
    println!("d: {:?}", d);
    println!("a: {:?}", a);
}

我明白了:

o: [7, 2, 3]
c: [8, 2, 3]
d: [9, 2, 3]
a: [1, 2, 3]

这三种方法都克隆了a的内容.

有什么不同吗?

推荐答案

For a reference to an instance of Copy there is no difference.
That is because for Copy types:

  1. *ref_to_val返回val的按位副本(并且不会使旧值无效).
  2. 派生的Clone个实施.对于Copy类型,将使用*实现.clone().
  3. 毯子ToOwned加厚.对于Clone类型,将使用.clone()实现.to_owned().

So it all boils down to bitwise copy.
This is your case.

If you want to understand how traits Deref, Clone, ToOwned work for !Copy types, you have to understand their purpose and read type-specific docs.
I believe String and str types are very representative !Copy types that will help you understand the magic. Eg. str is ToOwned, but not Deref or Clone. Your example won't work for these types.

Rust相关问答推荐

如何从Rust记录WASM堆内存使用情况?

borrow 和内部IntoIterator

访问Rust中的隐藏变量

关于Rust 中回归的逻辑

在执行其他工作的同时,从共享裁判后面的VEC中删除重复项

如何向下转换到MyStruct并访问Arc Mutex MyStruct实现的方法?

如何实现Deref;多次;?

`actix-web` 使用提供的 `tokio` 运行时有何用途?

找不到 .has_func 或 .get_func 的 def

为什么编译器看不到这个 `From` impl?

如何为整数切片定义一个带有额外函数的特性别名?

Rust编译器通过哪些规则来确保锁被释放?

以 `static` 为前缀的闭包是什么意思?我什么时候使用它?

在 Rust 中,将可变引用传递给函数的机制是什么?

仅当满足外部条件时如何添加到 actix web 的路由

当我在 struct 中存储异步函数时,为什么它需要生命周期

使用 `.` 将 T 转换为 &mut T?

返回 &str 但不是 String 时,borrow 时间比预期长

为什么当borrow 变量发生变化时,borrow 变量不会改变?

在 macro_rules 中转义 $ 美元符号