gpt4 book ai didi

arrays - Rust-如何初始化包含HashSet字段的结构数组?

转载 作者:行者123 更新时间:2023-12-03 11:43:17 26 4
gpt4 key购买 nike

我有带有Instance字段的HashSet结构,用于存储无序数字,并易于删除和添加重复项控件。

然后是另一个名为Matrix的结构,它包含Instance结构的二维数组。

我在trait中创建了new()方法,以便Instance在数组初始化中使用,但是使用此方法会在编译期间出错,并说HashSet没有实现Copy特质。

这是代码:

#![allow(unused)]
use std::collections::HashSet;

struct Instance {
ids: HashSet<u8>,
value: u8,
}

trait IsInstance {
fn new() -> Instance;
}

impl IsInstance for Instance {
fn new() -> Instance {
Instance {
ids: [1, 2, 3, 5].iter().cloned().collect(),
value: 0,
}
}
}

/*
Line below is commented due to error:

error[E0204]: the trait `Copy` may not be implemented for this type
--> src/main.rs:26:6
|
5 | ids: HashSet,
| ---------------- this field does not implement `Copy`
...
26 | impl Copy for Instance {}
| ^^^^

*/
//impl Copy for Instance {}

impl Clone for Instance {
fn clone(&self) -> Instance {
Instance {
ids: self.ids,
value: self.value,
}
}
}

struct Matrix {
instances: [[Instance; 4]; 4],
status: u8,
}

fn main() {
let mut m = Matrix {
instances: [[Instance::new(); 4]; 4],
status: 0,
};
}

编译此错误:
error[E0507]: cannot move out of `self.ids` which is behind a shared reference
--> src/main.rs:42:18
|
42 | ids: self.ids,
| ^^^^^^^^ move occurs because `self.ids` has type `std::collections::HashSet<u8>`, which does not implement the `Copy` trait

error[E0277]: the trait bound `Instance: std::marker::Copy` is not satisfied
--> src/main.rs:60:22
|
60 | instances : [[Instance::new(); 4]; 4],
| ^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `Instance`
|
= note: the `Copy` trait is required because the repeated element will be copied

error[E0277]: the trait bound `[Instance; 4]: std::marker::Copy` is not satisfied
--> src/main.rs:60:21
|
60 | instances : [[Instance::new(); 4]; 4],
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `[Instance; 4]`
|
= note: the `Copy` trait is required because the repeated element will be copied

有什么方法可以正确初始化此数组吗?我显然错过了一些东西,但是没有发现 HashSet复制实现可用于数组。也许还有另一种方法可以实现这一目标?

最佳答案

I clearly missed something, but didn't find HashSet copy implementation working with arrays.



那是因为没有一个! Copy表示类型可以逐位复制。像 HashSet<T>这样的类型不可能是这种情况。但是, HashSet<T>是默认可初始化的。结合数组(目前少于32个元素)也可以默认初始化的事实,可以使用以下命令:

let mut m = Matrix {
instances: Default::default(),
status: 0,
};

如果您添加

impl Default for Instance {
fn default() -> Self {
Self::new()
}
}

( Permalink to the playground)

关于arrays - Rust-如何初始化包含HashSet字段的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61309293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com