3 ms·
You have a trait Foo that has a function f() And then you have Bar and Baz that implement trait Foo. Example: pub trait Foo { // fn f(&self) -> S
by unionpivo 6y ago
You have a trait Foo that has a function f()
And then you have Bar and Baz that implement trait Foo.
Example:
pub trait Foo {
//
fn f(&self) -> String;
// Default implementation, can be overriden
fn banana(&Self) -> String {
String::from("BananaNjam!")
}
}
pub struct Baz {
pub BazThingy: String,
pub Whatever: String,
}
impl Foo for Baz {
fn f(&self) -> String {
format!("{} {}", self.BazThing, self.Whatever)
}
}
pub struct Bar {
pub Bar: String,
pub Tralala: String,
}
impl Foo for Bar {
fn f(&self) -> String {
format!("{} {}", self.Bar, self.Tralala)
}
}
// Now function that uses Foo, could be any object that implements foo
pub fn FooFighter( item: &impl Foo) {
println!("FooFighters rocks because {}", item.f() );
}
The neat thing is that Bar and Baz does not have to share all of the traits. SO you can have default trait lets sey Debug, that prints object, on most objects, but Foo only on a few, if that makes sense