1 | //! An example showing off the usage of `Deserialize` to automatically decode |
2 | //! TOML into a Rust `struct` |
3 | |
4 | #![deny (warnings)] |
5 | #![allow (dead_code)] |
6 | |
7 | use serde_derive::Deserialize; |
8 | |
9 | /// This is what we're going to decode into. Each field is optional, meaning |
10 | /// that it doesn't have to be present in TOML. |
11 | #[derive(Debug, Deserialize)] |
12 | struct Config { |
13 | global_string: Option<String>, |
14 | global_integer: Option<u64>, |
15 | server: Option<ServerConfig>, |
16 | peers: Option<Vec<PeerConfig>>, |
17 | } |
18 | |
19 | /// Sub-structs are decoded from tables, so this will decode from the `[server]` |
20 | /// table. |
21 | /// |
22 | /// Again, each field is optional, meaning they don't have to be present. |
23 | #[derive(Debug, Deserialize)] |
24 | struct ServerConfig { |
25 | ip: Option<String>, |
26 | port: Option<u64>, |
27 | } |
28 | |
29 | #[derive(Debug, Deserialize)] |
30 | struct PeerConfig { |
31 | ip: Option<String>, |
32 | port: Option<u64>, |
33 | } |
34 | |
35 | fn main() { |
36 | let toml_str = r#" |
37 | global_string = "test" |
38 | global_integer = 5 |
39 | |
40 | [server] |
41 | ip = "127.0.0.1" |
42 | port = 80 |
43 | |
44 | [[peers]] |
45 | ip = "127.0.0.1" |
46 | port = 8080 |
47 | |
48 | [[peers]] |
49 | ip = "127.0.0.1" |
50 | "# ; |
51 | |
52 | let decoded: Config = basic_toml::from_str(toml_str).unwrap(); |
53 | println!("{:#?}" , decoded); |
54 | } |
55 | |