struct - 如何为自定义结构实现复制特征?

标签 struct rust traits

<分区>

我有自己的自定义结构 - 事务,我希望可以复制它。

This fails because Vec does not implement Copy for any T. 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() 
{
}

最佳答案

我已经解决了这个问题: 我用表 [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
    }
}

关于struct - 如何为自定义结构实现复制特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58428100/

相关文章:

c++ - rust-bindgen 绑定(bind)引发 SIGSEGV

rust - 如何将 `Arc<dyn SubTrait>` 转换为 `Arc<dyn SuperTrait >` ?

rust - 我可以创建一个编译错误来检查一个特征是否有另一个特征作为超特征吗?

generics - 为什么我不能在带有类型参数的特征上添加一揽子暗示?

c - 在 C 中使一个指针指向另一个指针所指向的内容

c++ - C - 字符数组初始化

c - 结构指针变为 NULL ? (C)

rust - 将结构的多个字段与 `None` 匹配的最简单方法

c++ - C++中的继承特性

rust - Some(v) 和 Some(&v) 有什么区别?