繁体   English   中英

Rust中不满足特征限制

[英]The trait bound is not satisfied in Rust

我正在尝试在Rust中编写一个Tic Tac Toe游戏,但是这个用于更改字段的功能不起作用,我不知道它有什么问题:

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

原因是在笔记中给出的:

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变量的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM