Created
July 17, 2018 17:22
-
-
Save rust-play/60e6687038547e2c5de210dd474601df to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// yay, Dan! | |
// traits are like type classes, and type classes are like interfaces | |
// ' the turbofish ' | |
// monomorphization ? | |
// oh ya | |
// it's how we turn templates into single fn's | |
trait MyTrait{ | |
fn afunc(&self) -> String; | |
} | |
struct Person{ | |
name: String, | |
age: u8, | |
} | |
impl Person { | |
fn new() -> Self{ | |
Person { name: String::from("Bobbo"), age: 0 } | |
} | |
} | |
impl MyTrait for Person{ | |
fn afunc(&self) -> String { | |
format!("{} is my name and I'm {} yo", self.name, self.age) | |
} | |
} | |
// hot shit, generics -- t is type ref to T | |
fn print_it<T: MyTrait>(t : &T){ | |
println!("{}", t.afunc()); | |
} | |
// trait object? other way of writing this | |
// dynamic dispatch -- avoids need to recompile code | |
fn print_greeting(t: &dyn MyTrait){ | |
println!("{}", t.afunc()); | |
} | |
fn main(){ | |
let p = Person::new(); | |
print_it(&p); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment