Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Hands on the Rust Library Serde

Tips and Traps

  1. Rust crates serde and ron are popular serialization/deserialization libraries.

Dependencies

In [9]:
:timing
:sccache 1
:dep serde = { version = "1.0", features = ["derive"] }
In [10]:
:dep serde_json = "1.0"

Serialization

In [12]:
use serde::{Serialize, Deserialize};
In [13]:
#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}
In [17]:
let point = Point { x: 1, y: 2 };
let s = serde_json::to_string(&point).unwrap();
s
Out[17]:
"{\"x\":1,\"y\":2}"
In [18]:
println!("Point serialized = {}", s);
Point serialized = {"x":1,"y":2}

Deseriallization

In [19]:
let p2: Point = serde_json::from_str(&s).unwrap();
p2
Out[19]:
Point { x: 1, y: 2 }
In [20]:
println!("Point deserialized = {:?}", p2);
Point deserialized = Point { x: 1, y: 2 }
In [ ]:

Comments