【问题标题】:The trait bound is not satisfied in RustRust 不满足 trait bound
【发布时间】:2016-08-29 15:50:49
【问题描述】:

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

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。

【问题讨论】:

    标签: rust


    【解决方案1】:

    原因在备注中告诉你:

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

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 1970-01-01
      • 2021-12-04
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多