Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.