Skip to content

Instantly share code, notes, and snippets.

@matthewphilyaw
Created March 18, 2014 11:05
Show Gist options
  • Save matthewphilyaw/9617966 to your computer and use it in GitHub Desktop.
Save matthewphilyaw/9617966 to your computer and use it in GitHub Desktop.
use of traits
use std::fmt;
struct Name {
first: ~str,
last: ~str
}
// I'm printing a string here, but
// in reality this could be binary output
impl fmt::Binary for Name {
fn fmt(obj: &Name, f: &mut fmt::Formatter) {
write!(f.buf, "{}, {}", obj.last, obj.first)
}
}
impl fmt::Default for Name {
fn fmt(obj: &Name, f: &mut fmt::Formatter) {
write!(f.buf, "(first: {}, last: {})", obj.first, obj.last)
}
}
fn main() {
let x = Name { first: ~"Matthew", last: ~"Philyaw" };
// print default
println!("{}", x);
// print binary
println!("{:t}", x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment