Last active
February 8, 2016 21:27
-
-
Save lukaspustina/6f6d20628067471fe938 to your computer and use it in GitHub Desktop.
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
extern crate rustc_serialize; | |
use rustc_serialize::{Decodable, Encodable, json}; | |
use rustc_serialize::json::Json; | |
#[derive(RustcDecodable, RustcEncodable, Debug)] | |
pub enum Message { | |
First {msg: FirstMsg}, | |
Second {msg: SecondMsg} | |
} | |
#[derive(RustcDecodable, RustcEncodable, Debug)] | |
pub struct FirstMsg { | |
pub a_string: String, | |
pub a_int: i64 | |
} | |
#[derive(RustcDecodable, RustcEncodable, Debug)] | |
pub struct SecondMsg { | |
pub a_float: f32 | |
} | |
fn encode(msg: &Message) -> String { | |
json::encode(msg).unwrap() | |
} | |
fn decode(text: &str) -> Message { | |
json::decode(text).unwrap() | |
} | |
fn process(msg: Message) { | |
match msg { | |
Message::First{ msg } => println!("First {} {}", msg.a_string, msg.a_int), | |
Message::Second{ msg } => println!("Second {}", msg.a_float), | |
} | |
} | |
fn main() { | |
let first = Message::First{ msg: FirstMsg { a_string: "anne".to_string(), a_int: 42 } }; | |
let second = Message::Second{ msg: SecondMsg { a_float: 42.0 } }; | |
println!("First: '{:?}', Second: '{:?}'", first, second); | |
let encoded_first = encode(&first); | |
let encoded_second = encode(&second); | |
println!("First: '{}', Second: '{}'", encoded_first, encoded_second); | |
let first_copy = decode(&encoded_first); | |
let second_copy = decode(&encoded_second); | |
println!("First: '{:?}', Second: '{:?}'", first_copy, second_copy); | |
process(first_copy); | |
process(second_copy); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment