首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rust中的特征界限不满足

Rust中的特征界限不满足
EN

Stack Overflow用户
提问于 2016-08-29 23:50:49
回答 1查看 10.3K关注 0票数 5

我正在尝试用Rust写一个Tic Tac Toe游戏,但是这个改变字段的函数不起作用,我不知道它有什么问题:

代码语言:javascript
运行
复制
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;
}

我得到了这些错误:

代码语言:javascript
运行
复制
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中,我得到了以下错误:

代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-29 23:54:50

在注释中给出了原因:

代码语言:javascript
运行
复制
note: slice indices are of type `usize`
代码语言:javascript
运行
复制
slice indices are of type `usize` or ranges of `usize`

您需要将i32值强制转换为usize,例如:

代码语言:javascript
运行
复制
table[(field - 1) as usize]

或者,如果在您的应用程序中有意义,可以考虑使用usize作为field变量的类型。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39210311

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档