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

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

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

这失败,因为Vec没有为任何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() 
{
}
struct rust traits
1个回答
0
投票

我已经解决了这个问题:我用过桌子[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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.