Skip to content

Instantly share code, notes, and snippets.

@jvshahid
Last active December 27, 2015 07:59
Show Gist options
  • Save jvshahid/7292840 to your computer and use it in GitHub Desktop.
Save jvshahid/7292840 to your computer and use it in GitHub Desktop.
rust trait implementation
trait HasName {
fn get_name(&self) -> ~str;
}
trait HasGreeting {
fn get_greeting(&self) -> ~str;
}
impl <T: HasName> HasGreeting for T {
fn get_greeting(&self) -> ~str {
"welcome: " + self.get_name()
}
}
struct Foo {
priv name: ~str
}
impl HasName for Foo {
fn get_name(&self) -> ~str {
self.name.clone()
}
}
fn main() {
let foo1 = Foo{name: ~"Shahid"};
println(foo1.get_greeting());
let foo2 = ~Foo{name: ~"John"};
println((*foo2).get_greeting());
// the following line doesn't compile
// println(foo2.get_greeting());
//
// foo.rs:29:12: 29:32 error: failed to find an implementation of trait HasName for ~Foo
// foo.rs:29 println(foo2.get_greeting());
// ^~~~~~~~~~~~~~~~~~~~
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment