因此,我试图构建一个自定义类型的向量向量,我试图为它实现一个缺省值,并使用for循环实现了成功的。
let mut data: Vec<Vec<Cell>> = Vec::new();
for _i in 0..63 {
let mut row: Vec<Cell> = Vec::with_capacity(64);
for _j in 0..63 {
row.push(Cell::default())
}
data.push(row);
}我觉得这个代码可以用一些功能样式和interators来完成,所以我决定这样做:
let data: Vec<Vec<Cell>> = Vec::with_capacity(64)
.iter_mut()
.map(|mut x: &mut Vec<Cell>| {
x = Vec::with_capacity(64)
.iter_mut()
.map(|mut y: Cell| y = Cell::default())
.collect()
})
.collect();通过这个,我得到了一个类似于这样的错误:
error[E0631]: type mismatch in closure arguments
--> src/types.rs:124:26
|
124 | .map(|mut y: Cell| y = Cell::default())
| ^^^ ------------- found signature defined here
| |
| expected due to this
|
= note: expected closure signature `fn(&mut _) -> _`
found closure signature `fn(types::cell::Cell) -> _`
note: required by a bound in `map`
--> /home/naitik/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:779:12
|
779 | F: FnMut(Self::Item) -> B,
| ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `map`我不明白这里的问题。到底是什么?我能做些什么来解决这个问题?
发布于 2022-10-29 20:50:09
你误解了Vec::with_capacity的工作原理。它实际上不会将任何内容放入可以迭代并分配给它的vec中。您希望将Cell::default映射到某物上,然后将其收集到vec中。一些东西并不重要,只要有64个,那么一个范围就行了:
let data: Vec<Vec<Cell>> = (0..64)
.map(|_| (0..64).map(|_| Cell::default()).collect())
.collect();collect应该希望自己从范围的TrustedLen中找出所需的容量,以避免不必要的重新分配。
不过,我怀疑这是否比程序性办法更好。在我看来,这似乎不那么清晰,也很难修改。坚持好的循环是我的两分钱。
如果Cell是Clone或Copy,您甚至可以这样做:
let data: Vec<Vec<Cell>> = vec![vec![Cell::default(); 64]; 64];极大极小。
https://stackoverflow.com/questions/74248678
复制相似问题