Trait core::clone::Clone1.0.0[][src]

pub trait Clone: Sized {
    #[must_use = "cloning is often expensive and is not expected to have side effects"]
    fn clone(&self) -> Self;

    fn clone_from(&mut self, source: &Self) { ... }
}
Expand description

通用的 trait,用于显式复制对象。

Copy 的不同之处在于 Copy 是隐式的并且是廉价的按位复制,而 Clone 始终是显式的并且可能昂贵也可能不昂贵。 为了强制执行这些特性,Rust 不允许您重新实现 Copy,但是您可以重新实现 Clone 并运行任意代码。

由于 CloneCopy 更通用,因此您可以自动将 Copy 设为 Clone

Derivable

如果所有字段均为 Clone,则此 trait 可以与 #[derive] 一起使用。Clonederived 实现在每个字段上调用 clone

对于泛型结构体,#[derive] 通过在泛型参数上添加绑定的 Clone 有条件地实现 Clone

// `derive` T 为 Clone 时,为 Reading<T> 实现 Clone。
#[derive(Clone)]
struct Reading<T> {
    frequency: T,
}
Run

如何实现 Clone?

Copy 类型应该实现 Clone 的简单实现。更正式地: 如果 T: Copyx: Ty: &T,则 let x = y.clone(); 等效于 let x = *y;。 手动执行时应注意保持不变。但是,不安全的代码一定不能依靠它来确保内存安全。

一个示例是持有函数指针的泛型结构体。在这种情况下,不能对 Clone 的实现进行派生操作,而可以将其实现为:

struct Generate<T>(fn() -> T);

impl<T> Copy for Generate<T> {}

impl<T> Clone for Generate<T> {
    fn clone(&self) -> Self {
        *self
    }
}
Run

其他实现者

除了下面列出的 实现者 外,以下类型还实现了 Clone:

  • 函数项类型 (即,为每个函数定义的不同类型)
  • 函数指针类型 (例如 fn() -> i32)
  • 如果项类型也实现 Clone (例如 [i32; 123456]),则所有大小的数组类型
  • 如果每个组件还实现 Clone (例如 ()(i32, bool)),则为元组类型
  • 闭包类型,如果它们没有从环境中捕获任何值,或者所有此类捕获的值本身都实现了 Clone。 请注意,由共享引用捕获的变量始终实现 Clone (即使引用对象没有实现),而由变量引用捕获的变量从不实现 Clone

Required methods

返回值的副本。

Examples

let hello = "Hello"; // &str 实现克隆

assert_eq!("Hello", hello.clone());
Run

Provided methods

source 执行复制分配。

a.clone_from(&b) 在功能上等效于 a = b.clone(),但是可以重写以重用 a 的资源,以避免不必要的分配。

Implementors

This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on AArch64 only.
This is supported on ARM only.
This is supported on ARM only.
This is supported on ARM only.
This is supported on ARM only.
This is supported on PowerPC or PowerPC-64 only.
This is supported on PowerPC or PowerPC-64 only.
This is supported on PowerPC or PowerPC-64 only.
This is supported on PowerPC or PowerPC-64 only.
This is supported on WebAssembly only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.
This is supported on x86 or x86-64 only.

Panics

如果值当前是可变借用的,则出现 panic。

Panics

如果当前 other 是可变借用的,则会 panic。

共享的引用可以被克隆,但是可变引用 不能!

共享的引用可以被克隆,但是可变引用 不能!