本文介绍了Rust 不满足 trait bound的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用 Rust 编写一个 Tic Tac Toe 游戏,但是这个用于更改字段的功能不起作用,我不知道它有什么问题:
I'm trying to write a Tic Tac Toe game in Rust, but this function for changing a field doesn't work and I don't know what's wrong with it:
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 中,我收到以下错误:
In later versions of Rust, I get these errors:
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
.
This is my first project in Rust so I don't have much experience with it. I tried to change the field to u32
too.
推荐答案
原因在注释中给你:
note: slice indices are of type `usize`
slice indices are of type `usize` or ranges of `usize`
您需要将 i32
值强制转换为 usize
,例如:
You need to cast the i32
value to usize
, for example:
table[(field - 1) as usize]
或者,如果在您的应用程序中有意义,请考虑使用 usize
作为 field
变量的类型.
Alternatively, consider using usize
as the type of the field
variable, if it makes sense in your application.
这篇关于Rust 不满足 trait bound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!