Skip to content

Instantly share code, notes, and snippets.

@tkrs
Created May 25, 2017 04:48
Show Gist options
  • Select an option

  • Save tkrs/2c6b737461db5ebfeb6cd0541fdac04c to your computer and use it in GitHub Desktop.

Select an option

Save tkrs/2c6b737461db5ebfeb6cd0541fdac04c to your computer and use it in GitHub Desktop.
Type classes demo in Rust
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

tkrs commented May 25, 2017

Copy link
Copy Markdown
Author
rust-tut:master* λ cargo run -q src/main.rs
Response { req: "foo", msg: "run F" }
Response { req: "bar", msg: "run G" }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment