代码之家  ›  专栏  ›  技术社区  ›  Michał Hanusek

如何实现自定义结构的复制特性?

  •  0
  • Michał Hanusek  · 技术社区  · 6 年前

    我有我的自定义结构事务,我想我可以复制它。

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

    如何实现复制到Vec和my struct。我想举个例子。

    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() 
    {
    }
    
    0 回复  |  直到 6 年前
        1
  •  -2
  •   Michał Hanusek    6 年前

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