如何为自定义结构实现复制特征?
How to implement Copy trait for Custom struct?
我有我的自定义结构 - 交易,我想复制它。
This fails because Vec does not implement Copy for any T. E0204
如何实现复制到 Vec 和我的结构。我要举个例子。
#[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
}
}
我有我的自定义结构 - 交易,我想复制它。
This fails because Vec does not implement Copy for any T. E0204
如何实现复制到 Vec 和我的结构。我要举个例子。
#[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
}
}