我试图在Rust写一个Tic Tac Toe游戏,但这个改变字段的功能不起作用,我不知道它有什么问题:< / p>
fn change_field(mut table: [char; 9], field: i32, player: char) -> bool {
if field > 0 && field < 10 {
if table[field - 1] == ' ' {
table[field - 1] = player;
return true;
} else {
println!("That field isn't empty!");
}
} else {
println!("That field doesn't exist!");
}
return false;
}
我收到了这些错误:
src/main.rs:16:12: 16:26 error: the trait bound `[char]: std::ops::Index<i32>` is not satisfied [E0277]
src/main.rs:16 if table[field-1] == ' ' {
^~~~~~~~~~~~~~
src/main.rs:16:12: 16:26 help: run `rustc --explain E0277` to see a detailed explanation
src/main.rs:16:12: 16:26 note: slice indices are of type `usize`
src/main.rs:17:13: 17:27 error: the trait bound `[char]: std::ops::Index<i32>` is not satisfied [E0277]
src/main.rs:17 table[field-1] = player;
^~~~~~~~~~~~~~
src/main.rs:17:13: 17:27 help: run `rustc --explain E0277` to see a detailed explanation
src/main.rs:17:13: 17:27 note: slice indices are of type `usize`
src/main.rs:17:13: 17:27 error: the trait bound `[char]: std::ops::IndexMut<i32>` is not satisfied [E0277]
src/main.rs:17 table[field-1] = player;
^~~~~~~~~~~~~~
在Rust的更高版本中,我收到了以下错误:
error[E0277]: the trait bound `i32: std::slice::SliceIndex<[char]>` is not satisfied
--> src/main.rs:3:12
|
3 | if table[field - 1] == ' ' {
| ^^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[char]>` is not implemented for `i32`
= note: required because of the requirements on the impl of `std::ops::Index<i32>` for `[char]`
error[E0277]: the trait bound `i32: std::slice::SliceIndex<[char]>` is not satisfied
--> src/main.rs:4:13
|
4 | table[field - 1] = player;
| ^^^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[char]>` is not implemented for `i32`
= note: required because of the requirements on the impl of `std::ops::Index<i32>` for `[char]`
这是我在Rust的第一个项目,所以我没有多少经验。我也尝试将字段更改为u32
。
答案 0 :(得分:7)
原因是在笔记中给出的:
note: slice indices are of type `usize`
slice indices are of type `usize` or ranges of `usize`
您需要将i32
值转换为usize
,例如:
table[(field - 1) as usize]
或者,如果在您的应用中有意义,请考虑使用usize
作为field
变量的类型。