Created
July 25, 2018 19:02
-
-
Save rust-play/5ad18b429f0c1bde84c17e18184273e9 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
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