enums - "error: trait bounds are not allowed in structure definitions"尝试使用多态性时

标签 enums rust polymorphism rust-obsolete

Editor's note: This question was asked before Rust 1.0 and before certain features were implemented. The code as-is works today.

我正在用 Rust 编写棋盘游戏 AI。游戏有多个规则集,我希望将规则逻辑与棋盘布局分开(它们目前是混合的)。在像 Ruby 这样的语言中,我会让不同的规则集实现相同的接口(interface)。在 Rust 中,我考虑过使用特征并参数化 Board使用我想要使用的规则集(例如 Board<Rules1>::new() )。

在结构中保存实现此特征的对象(如 Board )是不允许的。我可以打开 Rules进入 enum ,但它对我来说看起来有点乱,因为我无法为枚举的成员定义单独的实现。使用模式匹配会起作用,但这会沿函数轴而不是沿结构轴拆分功能。这只是我必须忍受的事情还是有某种方式?

下面的代码是我想使用的:

pub struct Rules1;
pub struct Rules2;

trait Rules {
    fn move_allowed() -> bool;
}

impl Rules for Rules1 {
    fn move_allowed() -> bool {
        true
    }
}

impl Rules for Rules2 {
    fn move_allowed() -> bool {
        false
    }
}

struct Board<R: Rules> {
    rules: R
}

fn main() {}

它会产生以下错误:

test.rs:20:1: 22:2 error: trait bounds are not allowed in structure definitions
test.rs:20 struct Board<R: Rules> {
test.rs:21     rules: R
test.rs:22 }
error: aborting due to previous error

最佳答案

问题中提供的代码适用于所有最新版本的 Rust,现在允许结构上的特征界限。原来的答案也仍然有效。


您需要在 trait 实现中改进它,而不是在结构定义中。

pub struct Rules1;
pub struct Rules2;

trait Rules {
    fn move_allowed(&self) -> bool;
}

impl Rules for Rules1 {
    fn move_allowed(&self) -> bool {
        true
    }
}

impl Rules for Rules2 {
    fn move_allowed(&self) -> bool {
        false
    }
}

struct Board<R> {
    rules: R,
}

impl<R: Rules> Board<R> {
    fn move_allowed(&self) -> bool {
        self.rules.move_allowed()
    }
}

fn main() {
    let board = Board { rules: Rules2 };
    assert!(!board.move_allowed());
}

关于enums - "error: trait bounds are not allowed in structure definitions"尝试使用多态性时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24363369/

相关文章:

objective-c - 在 Objective-C 中声明和检查/比较(位掩码)枚举

java - 适合枚举的持久化数据

lua - 从要使用 FFI 调用的 Rust 函数返回字符串

java - 如何遍历类的数组列表

java - 实例化/从枚举返回时类型安全的接口(interface) (Java)

mysql - 使用 BIT 值将多列合并为一列

rust - 在Rust中实现超时

rust - Rust 错误 : cannot call a method whose type contains a self-type through an object

haskell - 模式匹配后多态性丢失

c++ - 如何在具有相同父类的两个类之间共享代码?