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/

相关文章:

rust - 我如何让 Cargo 将包的名称/版本保存到我的 "[dependencies]"文件的 "Cargo.toml"部分?

rust - 为什么 Fn 派生自 FnMut(派生自 FnOnce)?

generics - 如何在 Rust 中实现任意加运算符?

python - 如何在程序中添加过渡画面?

c++ - 如何简单分配不同结构的 vector ?

c++ - 如何在另一个模板化结构中使用模板化结构 (C++)

python - Python 中的 C 结构

c - 指向或不指向

rust - 为什么定义 RUSTFLAGS 会导致 .cargo/config 中的 rustflags 被忽略?

rust - 在向量中调用结构的特征方法时出现问题