我试图根据用户提供的索引(终端输入)替换数组元素,但我得到了下一个错误:
--> 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的新手,找不到这个错误的解决方案。提前感谢!
发布于 2020-03-07 03:56:51
找到了!我只需要像这样将movement转换为usize:
board[movement as usize] = fire;https://stackoverflow.com/questions/60570556
复制相似问题