Skip to content

Instantly share code, notes, and snippets.

@willurd
Forked from rust-play/playground.rs
Created July 26, 2018 05:41
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 willurd/460babfaa3f3597d688e6bc7758a0a28 to your computer and use it in GitHub Desktop.
Save willurd/460babfaa3f3597d688e6bc7758a0a28 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait Json {
fn to_string(&self) -> String;
}
trait Xml {
fn to_string(&self) -> String;
}
#[derive(Debug)]
struct Point2 {
x: i32,
y: i32
}
impl Xml for Point2 {
fn to_string(&self) -> String {
format!("<point x=\"{}\" y=\"{}\" />", self.x, self.y)
}
}
impl Json for Point2 {
fn to_string(&self) -> String {
format!("{{\"x\": {}, \"y\": {}}}", self.x, self.y)
}
}
// Prints:
// >> Point2 { x: 4, y: 5 }
// >> <point x="4" y="5" />
// >> {"x": 4, "y": 5}
// >> <point x="4" y="5" />
// >> {"x": 4, "y": 5}
fn main() {
let p = Point2 { x: 4, y: 5 };
println!("{:?}", p);
println!("{}", Xml::to_string(&p));
println!("{}", Json::to_string(&p));
println!("{}", (&p as &Xml).to_string());
println!("{}", (&p as &Json).to_string());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment