gpt4 book ai didi

rust - "type mismatch"在二维数组上循环

转载 作者:行者123 更新时间:2023-11-29 08:19:12 25 4
gpt4 key购买 nike

我无法编译这段代码:

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 - "type mismatch"在二维数组上循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050460/

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