From: Martin Pitt Date: Sat, 25 Sep 2021 06:59:37 +0000 (+0200) Subject: serde: Data types and initial serialization X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=commitdiff_plain;h=6b86f7f9dc3b179a09341af581e7af8b518beedc;ds=sidebyside serde: Data types and initial serialization --- diff --git a/serde/Cargo.toml b/serde/Cargo.toml new file mode 100644 index 0000000..64d55f5 --- /dev/null +++ b/serde/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "serde" +version = "0.1.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" diff --git a/serde/src/main.rs b/serde/src/main.rs new file mode 100644 index 0000000..0c9efe9 --- /dev/null +++ b/serde/src/main.rs @@ -0,0 +1,36 @@ +use serde::{Serialize, Deserialize}; + +#[derive(Serialize, Deserialize, Debug)] +enum Social { + Twitter(String), + ICQ(u64), + Nothing, +} + +#[derive(Serialize, Deserialize, Debug)] +struct Contact { + name: String, + phone: u32, + social: Social, +} + +type Contacts = Vec; + +fn build_contacts() -> Contacts { + vec![ + Contact { name: "John".to_string(), phone: 12345, social: Social::Twitter("@the_john".to_string()) }, + Contact { name: "Mary".to_string(), phone: 9876543, social: Social::ICQ(111234) }, + Contact { name: "Jane".to_string(), phone: 555555, social: Social::Nothing }, + ] +} + +fn create_contacts() { + let contacts = build_contacts(); + // FIXME: Use ? and return Result + let serialized = serde_json::to_string(&contacts).unwrap(); + println!("serialized: {}", serialized); +} + +fn main() { + create_contacts(); +}