根据索引替换数组元素

时间:2020-03-06 19:39:02

标签: rust

我试图根据用户(终端输入)提供的索引替换数组元素,但出现下一个错误:

  --> src/main.rs:30:17
   |
30 |                 board[movement] = fire;
   |                 ^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[char]>` is not implemented for `u32`
   = note: required because of the requirements on the impl of `std::ops::Index<u32>` for `[char]`

这是我的代码:

use std::io;
use std::io::Write;

fn main() {
    let mut board: [char; 9] = [' '; 9];
    let fire: char = '?';
    // let water: char = '?';

    let mut movement = String::new();
    let valid_cells = 1..9;

    loop {
        print!("Please input your movement: ");
        io::stdout().flush().unwrap();

        io::stdin()
            .read_line(&mut movement)
            .expect("Failed to read line!");

        let movement: u32 = match movement.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("That's not a valid number!");
                continue;
            }
        };

        match valid_cells.contains(&movement) {
            true => {
                board[movement] = fire;
            }
            _ => {
                println!("That's not a valid cell!");
                continue;
            }
        }

        for (i, x) in board.iter().enumerate() {
            print!("| {}: {}", i, x);
            if (i + 1) % 3 == 0 {
                println!("\n");
            }
        }

        if !board.contains(&' ') {
            break;
        }
    }
}

我是Rust的新手,无法找到解决此错误的方法。预先感谢!

2 个答案:

答案 0 :(得分:1)

您可以直接将其解析为usize

let movement: usize = match movement.trim().parse() {
    Ok(num) if valid_cells.contains(&num) => num,
    _ => {
        println!("That's not a valid cell!");
        continue;
    }
};

board[movement] = fire;

答案 1 :(得分:0)

找到了!我只需要像这样将movement投射到usize

board[movement as usize] = fire;