Arrays Rust-如何初始化包含HashSet字段的结构数组?
我有Arrays Rust-如何初始化包含HashSet字段的结构数组?,arrays,rust,hashset,Arrays,Rust,Hashset,我有Instancestruct和HashSet字段,用于存储无顺序的数字,并使用复制控件轻松删除和添加 然后还有另一个名为Matrix的结构,它包含实例结构的二维数组 我在trait中为实例创建了new()方法,以用于数组初始化,但使用此方法在编译过程中会出现错误,即HashSet未实现Copytrait 代码如下: #![允许(未使用)] 使用std::collections::HashSet; 结构实例{ id:HashSet, 值:u8, } 性状不稳定{ fn new()->实例; }
Instance
struct和HashSet
字段,用于存储无顺序的数字,并使用复制控件轻松删除和添加
然后还有另一个名为Matrix
的结构,它包含实例结构的二维数组
我在trait中为实例
创建了new()
方法,以用于数组初始化,但使用此方法在编译过程中会出现错误,即HashSet
未实现Copy
trait
代码如下:
#![允许(未使用)]
使用std::collections::HashSet;
结构实例{
id:HashSet,
值:u8,
}
性状不稳定{
fn new()->实例;
}
例如,impl-IsInstance{
fn new()->实例{
实例{
ID:[1,2,3,5].iter().cloned().collect(),,
值:0,
}
}
}
/*
由于错误,下面的行被注释:
错误[E0204]:此类型可能未实现特征“Copy”
-->src/main.rs:26:6
|
5 | ids:HashSet,
|------------此字段不实现“复制”`
...
26 | impl Copy,例如{}
| ^^^^
*/
//实例{}的impl复制
例如,impl克隆{
fn克隆(&self)->实例{
实例{
id:self.id,
价值:自我价值,
}
}
}
结构矩阵{
实例:[[Instance;4];4],
状态:u8,
}
fn main(){
设mut m=矩阵{
实例:[[Instance::new();4];4],
状态: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
error[E0507]:无法移出共享引用后面的'self.ids'
-->src/main.rs:42:18
|
42 | id:self.id,
|发生移动是因为'self.ids'的类型为'std::collections::HashSet',而该类型未实现'Copy'特性
错误[E0277]:未满足特性绑定的'Instance:std::marker::Copy'
-->src/main.rs:60:22
|
60个实例:[[Instance::new();4];4],
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^未为`实例实现特性`std::marker::Copy``
|
=注意:`Copy`特性是必需的,因为重复的元素将被复制
错误[E0277]:特性绑定的“[Instance;4]:std::marker::Copy”不满足
-->src/main.rs:60:21
|
60个实例:[[Instance::new();4];4],
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^[实例;4]`
|
=注意:`Copy`特性是必需的,因为重复的元素将被复制
有没有办法正确初始化这个数组?我显然错过了一些东西,但没有找到使用数组的HashSet
copy实现。也许还有其他方法可以实现这一点
我显然错过了一些东西,但没有找到使用数组的HashSet
copy实现
那是因为根本没有<代码>复制
表示类型可以逐位复制。这不可能是像HashSet
这样的类型。但是,HashSet
是默认可初始化的。结合数组(目前在32个元素下)也是默认可初始化的事实,您可以使用以下选项:
让mut m=矩阵{
实例:Default::Default(),
状态:0,
};
如果你加上
例如,impl默认值{
fn default()->Self{
Self::new()
}
}
()哦,这太好了,对我来说很有效。谢谢显而易见的问题是,有没有一种方法可以用于包含32个以上元素的数组?我只是好奇:)@Vix no。一旦const-generic稳定下来,最终可能会有: