循环在2D阵列上时“类型不匹配”

时间:2015-12-02 18:37:33

标签: rust

我无法编译此代码:

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`.

有人可以解释那个告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

简单。您只是错过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");
  }
}