]> piware.de Git - learn-rust.git/commitdiff
serde: Data types and initial serialization
authorMartin Pitt <martin@piware.de>
Sat, 25 Sep 2021 06:59:37 +0000 (08:59 +0200)
committerMartin Pitt <martin@piware.de>
Sat, 25 Sep 2021 06:59:37 +0000 (08:59 +0200)
serde/Cargo.toml [new file with mode: 0644]
serde/src/main.rs [new file with mode: 0644]

diff --git a/serde/Cargo.toml b/serde/Cargo.toml
new file mode 100644 (file)
index 0000000..64d55f5
--- /dev/null
@@ -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 (file)
index 0000000..0c9efe9
--- /dev/null
@@ -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<Contact>;
+
+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();
+}