我无法编译此代码:
fn main() {
let grid: [[Option<i32>;2];2] = [
[Some(1),Some(2)],
[None,Some(4)],
];
for row in grid.iter() {
for v in row.iter() {
match v {
Some(x) => print!("{}", x),
None => print!(" "),
}
}
print!("\n");
}
}
我收到此错误消息
Compiling array-2d v0.1.0 (file:///Users/paul/src/test/rust/array-2d)
src/main.rs:8:5: 13:6 error: type mismatch resolving `<core::slice::Iter<'_, core::option::Option<i32>> as core::iter::Iterator>::Item == core::option::Option<_>`:
expected &-ptr,
found enum `core::option::Option` [E0271]
src/main.rs: 8 for v in row.iter() {
src/main.rs: 9 match v {
src/main.rs:10 Some(x) => print!("{}", x),
src/main.rs:11 None => print!(" "),
src/main.rs:12 }
src/main.rs:13 }
src/main.rs:8:5: 13:6 note: in this expansion of for loop expansion
src/main.rs:7:3: 15:4 note: in this expansion of for loop expansion
src/main.rs:8:5: 13:6 help: run `rustc --explain E0271` to see a detailed explanation
error: aborting due to previous error
Could not compile `array-2d`.
有人可以解释一下,告诉我我做错了什么吗?
最佳答案
简单的。您只是错过了v
是一个引用。
pub fn main() {
let grid: [[Option<i32>;2];2] = [
[Some(1),Some(2)],
[None,Some(4)],
];
for row in grid.iter() {
for &v in row.iter() {
match v {
Some(x) => print!("{}", x),
None => print!(" "),
}
}
print!("\n");
}
// Keep in mind that i32 is Copy (but Option is not)
// and an Array of X is Copy if X is Copy,
// So there is no need to borrow v here, as follows:
let grid2: [[i32;2];2] = [
[1,2],
[0,4],
];
for row in grid2.iter() {
for v in row.iter() {
print!("{}", v);
}
print!("\n");
}
}
关于rust - 循环遍历2D数组时的“type mismatch”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34050460/