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

问题描述 投票:-1回答:1

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

// 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,
}
rust
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.