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

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

有人可以解释一下我做错了什么吗?

最佳答案

简单。你只是错过了 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/

相关文章:

rust - 返回一个 str - Rust Lifetimes

rust - Rust 中两个 float 与任意精度级别的比较

rust - 在 Rust 中通过提前返回来处理错误的惯用方法

创建一个 Rust 共享库,返回一个函数指针结构到 C 主程序

formatting - 格式化类型语法中的类型有什么作用?

generics - 未为类型`x`实现特征'x`

multidimensional-array - Rust ndarray,对拥有的值进行算术运算

enums - 匹配内部可变枚举的预期方法是什么?

debugging - 有没有办法在gdb或lldb中直接运行Cargo构建的程序?

rust - 如何在 Substrate FRAME 托盘内的结构中包含 <T as Trait>::Blocknumber