Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created November 18, 2018 20:15
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 rust-play/f187e1d7dc3c6e9290c63558c25bd7d3 to your computer and use it in GitHub Desktop.
Save rust-play/f187e1d7dc3c6e9290c63558c25bd7d3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait A {
fn greet(&self) {
println!("Hi! I am {}!", self.name());
}
fn name(&self) -> &str {
"A"
}
}
trait B: A {
fn name(&self) -> &str {
"B"
}
}
struct X {
name: &'static str,
}
struct Y {}
struct Z {}
impl A for X {}
impl B for X {
fn name(&self) -> &str {
self.name
}
}
impl A for Y {}
impl B for Y {
fn name(&self) -> &str {
A::name(self)
}
}
impl A for Z {}
impl B for Z {}
fn greet<T: B>(t: &T) {
t.greet();
}
fn main() {
let x = X { name: "X" };
let y = Y {};
let z = Z {};
greet(&x);
greet(&y);
greet(&z);
println!("x - {}", A::name(&x));
println!("x - {}", B::name(&x));
println!("y - {}", A::name(&y));
println!("y - {}", B::name(&y));
println!("z - {}", A::name(&z));
println!("z - {}", B::name(&z));
// error[E0034]: multiple applicable items in scope
// println!("z - {}", z.name());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment