"error: attribute boundaries are not allowed in the structure definitions" when trying to use polymorphism

Editor's Note: This question was asked before Rust 1.0 and before some functions were implemented. The as-code works today.

I am writing an AI card game in Rust. There are many sets of rules for the game, and I would like the rules logic to be separated from the board layout (they are currently mixed). In a language such as Ruby, I will have separate rule sets that implement the same interface. In Rust, I thought about using the Tag feature and parameterizing the Board with the rule set I want to use (e.g. Board<Rules1>::new() ).

Saving an object that implements this feature in a structure (for example, Board ) is not allowed. I could turn Rules into an enum , but for me it looks a little dirty because I cannot define separate implementations for enumeration members. Using pattern matching will work, but it shares functionality along the functional axis, rather than along the axis of the structure. Is this something I have to live with or is there somehow?

The following code is what I would 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() {} 

The following error is issued:

 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 
+7
polymorphism enums rust rust-obsolete
source share
1 answer

The code presented in this question works with all the latest versions of Rust; restrictions on structures are now available. The original answer is also retained.


You need to clarify this in the implementation of the characteristic, and not in the definition of structure.

 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()); } 
+10
source share

All Articles