0

I'm trying to replace an array element based on a index supplied by the user (terminal input) but I'm getting the next error:

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

And this is my code:

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;
        }
    }
}

I'm a total new to Rust and can't find the solution to this error. Thanks in advance!

2 Answers 2

1

You can just parse it as usize directly.

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I'll stick with this one, it's better than mine for sure.
0

Found it! I just had to cast movement to usize like this:

board[movement as usize] = fire;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.