Created
January 7, 2021 05:09
-
-
Save justanotherdot/464c31ab03189efb113df97b001ed8d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Fruit { | |
fn accept<A: FruitVisitor>(self, visitor: &mut A); | |
} | |
#[derive(Debug)] | |
struct Orange; | |
#[derive(Debug)] | |
struct Apple; | |
#[derive(Debug)] | |
struct Banana; | |
impl Fruit for Orange { | |
fn accept<A: FruitVisitor>(self, visitor: &mut A) { | |
visitor.visit_orange(self); | |
} | |
} | |
impl Fruit for Apple { | |
fn accept<A: FruitVisitor>(self, visitor: &mut A) { | |
visitor.visit_apple(self); | |
} | |
} | |
impl Fruit for Banana { | |
fn accept<A: FruitVisitor>(self, visitor: &mut A) { | |
visitor.visit_banana(self); | |
} | |
} | |
trait FruitVisitor { | |
// TODO refine A by bounding it to a marker trait impl on the above. | |
// fn visit<A>(self, fruit: A); | |
fn visit_orange(&mut self, orange: Orange); | |
fn visit_apple(&mut self, apple: Apple); | |
fn visit_banana(&mut self, banana: Banana); | |
} | |
#[derive(Debug)] | |
struct FruitPartitioner { | |
oranges: Vec<Orange>, | |
apples: Vec<Apple>, | |
bananas: Vec<Banana>, | |
} | |
impl FruitVisitor for FruitPartitioner { | |
// // Make a generic implementation. | |
// fn visit<A>(self, fruit: A) { | |
// // TODO. | |
// } | |
fn visit_orange(&mut self, orange: Orange) { | |
self.oranges.push(orange); | |
} | |
fn visit_apple(&mut self, apple: Apple) { | |
self.apples.push(apple); | |
} | |
fn visit_banana(&mut self, banana: Banana) { | |
self.bananas.push(banana); | |
} | |
} | |
fn main() { | |
let mut fruit_partitioner = FruitPartitioner { | |
oranges: vec![], | |
apples: vec![], | |
bananas: vec![], | |
}; | |
let f1 = Orange; | |
f1.accept(&mut fruit_partitioner); | |
let f1 = Apple; | |
f1.accept(&mut fruit_partitioner); | |
let f1 = Banana; | |
f1.accept(&mut fruit_partitioner); | |
let f1 = Banana; | |
f1.accept(&mut fruit_partitioner); | |
let f1 = Banana; | |
f1.accept(&mut fruit_partitioner); | |
let f1 = Orange; | |
f1.accept(&mut fruit_partitioner); | |
dbg!(fruit_partitioner); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment