Skip to content

Instantly share code, notes, and snippets.

@jlgerber
Created July 14, 2018 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlgerber/9765eaa0115bfece52e156bf1ea6f0a0 to your computer and use it in GitHub Desktop.
Save jlgerber/9765eaa0115bfece52e156bf1ea6f0a0 to your computer and use it in GitHub Desktop.
multiple implementations of same generic trait and how to apply
pub enum Entity {
Foo,
Bar,
}
pub trait ExtractEntity<T> {
fn extract_entity(&self, out: Entity) -> Option<T>;
}
pub trait ExtractEntity2<T> {
fn extract_entity2(&self) -> T;
}
#[derive(Debug)]
struct Foo {
foo_name: String
}
impl Foo {
pub fn new(foo_name: String) -> Foo {
Foo { foo_name }
}
}
#[derive(Debug)]
pub struct Bar {
bar_name: String
}
impl Bar {
pub fn new(bar_name: String) -> Bar {
Bar { bar_name }
}
}
#[derive(Debug)]
struct Bla {
foo: Foo,
bar: Bar,
}
impl ExtractEntity<Bar> for Bla {
fn extract_entity(&self, out: Entity) -> Option<Bar> {
if let Entity::Bar = out {
Some(Bar::new(self.bar.bar_name.clone()))
} else {
None
}
}
}
impl ExtractEntity2<Bar> for Bla {
fn extract_entity2(&self) -> Bar {
Bar::new(self.bar.bar_name.clone())
}
}
impl ExtractEntity<Foo> for Bla {
fn extract_entity(&self, out: Entity) -> Option<Foo> {
if let Entity::Foo = out {
Some(Foo::new(self.foo.foo_name.clone()))
} else {
None
}
}
}
impl ExtractEntity2<Foo> for Bla {
fn extract_entity2(&self) -> Foo {
Foo::new(self.foo.foo_name.clone())
}
}
fn main () {
let bla = Bla { foo: Foo{foo_name: "FOO".to_string()}, bar: Bar{bar_name: "BAR".to_string()}};
println!("{:?}", bla);
//let mut bar: Bar = Bar::new(String::new());
let bar: Bar = bla.extract_entity2();
let foo: Foo = bla.extract_entity2();
println!("foo {:?} bar {:?}", foo, bar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment