繁体   English   中英

如何在不使用 Copy 或 Clone 的情况下在 Rust 中克隆结构?

[英]How do I clone structs in Rust without using either Copy or Clone?

如何为这三种结构风格中的每一种创建深层副本?

// A unit struct
struct Thing;

// A tuple struct
struct Thingy(u8, i32);

// regular
struct Location {
    name: String,
    code: i32,
}

我可以在不使用CopyClone特征的情况下做到这一点吗? 如果已经定义了一个结构并且没有实现这些特征,是否有解决方法?

// without this:
#[derive(Copy, Clone)]
struct Location {
    name: String,
    code: i32,
}

单元结构不包含数据,因此“深拷贝”只是它的另一个实例: let thing_clone = Thing;

对于其他类型,您只需手动克隆字段并从克隆的字段中创建一个新对象。 假设ThingyLocation都有一个new方法:

let thingy_clone = Thingy::new(thingy.0, thingy.1);

let location_clone = Location::new(location.name.clone(), location.code);

请注意,我只为 String 字段显式编写了.clone() 那是因为 u8 和 i32 实现了Copy ,因此会在需要时自动复制。 无需显式复制/克隆。

也就是说,使用Clone特性绝对更惯用。 如果ThingThingyLocation是外部库的一部分,您可以提交错误报告,要求为这些结构实现Clone

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM