enums - Polymorphism in Rust -
enums - Polymorphism in Rust -
i'm writing board game ai in rust. there multiple rulesets game , i'd have rules logic separated board layout (they mixed). in language ruby i'd have separate rule sets implement same interface. in rust thought using trait , parameterizing board
ruleset want utilize (e.g. board<rules1>::new()
). saving object implements trait in struct (like board
) not allowed. of course of study turn rules
enum
, looks bit messy me then, because can't define separate implementations members of enum. using pattern matching work, splits functionality along function axis , not along struct axis. have live or there way?
the next code i'd use:
pub struct rules1; pub struct rules2; trait rules { fn move_allowed() -> bool; } impl rules rules1 { fn move_allowed() -> bool { true } } impl rules rules2 { fn move_allowed() -> bool { false } } struct board<r: rules> { rules: r } fn main() {}
it produces next error:
test.rs:20:1: 22:2 error: trait bounds not allowed in construction definitions test.rs:20 struct board<r: rules> { test.rs:21 rules: r test.rs:22 } error: aborting due previous error
the code presented in question works on recent versions of rust, trait bounds on structs allowed.
for reference, original reply follows:
pub struct rules1; pub struct rules2; trait rules { fn move_allowed(&self) -> bool; } impl rules rules1 { fn move_allowed(&self) -> bool { true } } impl rules 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() { allow board = board { rules: rules2 }; assert!(!board.move_allowed()); }
you need refine in trait implementation, not struct definition.
enums polymorphism rust
Comments
Post a Comment