Created
May 25, 2017 04:48
-
-
Save tkrs/2c6b737461db5ebfeb6cd0541fdac04c to your computer and use it in GitHub Desktop.
Type classes demo in Rust
This file contains hidden or 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 Gettable<A> { | |
| fn run(&self) -> A; | |
| } | |
| #[derive(Debug)] | |
| struct Request { | |
| a: String, | |
| } | |
| #[derive(Debug)] | |
| struct Response { | |
| req: String, | |
| msg: String, | |
| } | |
| #[derive(Debug)] | |
| struct F { | |
| a: String, | |
| } | |
| #[derive(Debug)] | |
| struct G { | |
| a: String, | |
| } | |
| trait Proc { | |
| fn run(&self) -> Response; | |
| } | |
| impl Proc for F { | |
| fn run(&self) -> Response { | |
| Response { | |
| req: self.a.to_owned(), | |
| msg: "run F".to_owned(), | |
| } | |
| } | |
| } | |
| impl Proc for G { | |
| fn run(&self) -> Response { | |
| Response { | |
| req: self.a.to_owned(), | |
| msg: "run G".to_owned(), | |
| } | |
| } | |
| } | |
| impl Gettable<F> for Request { | |
| fn run(&self) -> F { | |
| F { a: self.a.to_owned() } | |
| } | |
| } | |
| impl Gettable<G> for Request { | |
| fn run(&self) -> G { | |
| G { a: self.a.to_owned() } | |
| } | |
| } | |
| fn handle<T>(x: Request) -> Response | |
| where Request: Gettable<T>, | |
| T: Proc | |
| { | |
| let p = x.run(); | |
| p.run() | |
| } | |
| fn main() { | |
| let r = Request { a: "foo".to_owned() }; | |
| println!("{:?}", handle::<F>(r)); | |
| let r = Request { a: "bar".to_owned() }; | |
| println!("{:?}", handle::<G>(r)); | |
| } |
tkrs
commented
May 25, 2017
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment