Skip to content

Instantly share code, notes, and snippets.

@lukaspustina
Last active February 8, 2016 21:27
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 lukaspustina/6f6d20628067471fe938 to your computer and use it in GitHub Desktop.
Save lukaspustina/6f6d20628067471fe938 to your computer and use it in GitHub Desktop.
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