“错误:结构定义中不允许特征边界".尝试使用多态时 [英] "error: trait bounds are not allowed in structure definitions" when attempting to use polymorphism

查看:94
本文介绍了“错误:结构定义中不允许特征边界".尝试使用多态时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编者注:在Rust 1.0之前和实现某些功能之前,曾问过这个问题.代码按原样在今天可用.

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这样的语言中,我会让单独的规则集实现相同的接口.在Rust中,我考虑过使用特征并使用要使用的规则集(例如Board<Rules1>::new())参数化Board.

I'm writing a board game AI in Rust. There are multiple rulesets for the game and I'd like to have the rules logic separated from the board layout (they are currently mixed). In a language like Ruby, I'd have the separate rule sets implement the same interface. In Rust I thought about using a trait and parameterizing the Board with the ruleset I want to use (e.g. Board<Rules1>::new()).

不允许保存在结构中实现此特征的对象(如Board).我可以将Rules转换为enum,但是对我来说有点混乱,因为我无法为枚举成员定义单独的实现.使用模式匹配会起作用,但是会沿功能轴而不是沿结构轴拆分功能.这只是我必须忍受的东西吗?还是有某种方式?

Saving an object that implements this trait in a struct (like Board) is not allowed. I could turn the Rules into an enum, but it looks a bit messy to me because I can't define separate implementations for the members of the enum. Using pattern matching would work, but that splits the functionality along the function axis and not along the struct axis. Is this just something I have to live with or there some way?

以下是我要使用的代码:

The following code is what I'd like to use:

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的所有最新版本,现在允许使用结构的特征界线.原始答案也仍然有效.

The code presented in the question works on all recent versions of Rust, trait bounds on structs are now allowed. The original answer is also still valid.

您需要在trait实现中而不是在结构定义中进行优化.

You need to refine that in the trait implementation, not the struct definition.

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());
}

这篇关于“错误:结构定义中不允许特征边界".尝试使用多态时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆