【问题标题】:How to implement Copy trait for Custom struct? [duplicate]如何为自定义结构实现复制特征? [复制]
【发布时间】:2019-10-17 08:26:15
【问题描述】:

我有我的自定义结构 - 交易,我希望我可以复制它。

这失败了,因为 Vec 没有为任何 T 实现 Copy。E0204

如何实现对 Vec 和我的结构的复制。我在问一个例子。

Playground

#[derive(PartialOrd, Eq, Hash)]
struct Transaction {
    transaction_id: Vec<u8>,
    proto_id: Vec<u8>,
    len_field: Vec<u8>,
    unit_id: u8,
    func_nr: u8,
    count_bytes: u8,
}

impl Copy for Transaction { }

impl Clone for Transaction {
    fn clone(&self) -> Transaction {
        *self
    }
}

impl PartialEq for Transaction {
    fn eq(&self, other: &Self) -> bool {
        self.unit_id == other.unit_id
            && self.func_nr == other.func_nr
            && self.count_bytes == other.count_bytes
    }
}

fn main() 
{
}

【问题讨论】:

  • 您是否真的想在每次使用事务结构时复制三个向量,每次将其传递给函数时?你真正的问题是什么?复制结构不涉及使用 Copy 特征。
  • 你的意思是Copy 还是Clone,在 rust 中有点不同。
  • @edwardw 我不认为这是重复的,因为这是 IMO 的 XY 问题。
  • @DenysSéguret 这个问题的答案也回答了这个 IMO。
  • 文档显示没有实现'Copy' Vec trait。我明白这应该被实施。

标签: struct rust traits


【解决方案1】:

我解决了这个问题: 我使用了表格 [u8; 2] 而不是 Vec 。

但我还是不明白为什么你不能在结构中使用向量并复制它。

#[derive(PartialOrd, Eq, Copy, Clone, Hash)]
struct Transaction {
    transaction_id: [u8; 2],
    proto_id:  [u8; 2],
    len_field: [u8; 2],
    unit_id: u8,
    func_nr: u8,
    count_bytes: u8,
}

impl PartialEq for Transaction {
    fn eq(&self, other: &Self) -> bool {
        self.unit_id == other.unit_id
            && self.func_nr == other.func_nr
            && self.count_bytes == other.count_bytes
    }
}

【讨论】:

  • “但我还是不明白为什么你不能在结构中使用向量并复制它。”只需阅读副本 - -
猜你喜欢
  • 2021-05-18
  • 2015-01-12
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2011-02-12
相关资源
最近更新 更多