-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadvanced.rs
79 lines (70 loc) · 2.11 KB
/
advanced.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use fast_config::{Config, ConfigSetupOptions};
use fast_config::error::{ConfigError, DataParseError};
use serde::{Serialize, Deserialize};
// Sub-structs
#[derive(Serialize, Deserialize)]
pub struct Person {
pub name: String,
pub age: u64,
pub skill_issue: bool
}
// Creating a config struct to store our data
#[derive(Serialize, Deserialize)]
pub struct MyData {
pub student_debt: i32,
pub person: Person
}
// Setting the default values for the data
impl Default for MyData {
fn default() -> Self {
Self {
student_debt: 20,
person: Person {
name: "Joe Mama".into(),
age: 400,
skill_issue: true
}
}
}
}
fn main() {
// Initializing a logging system (needed to show some warnings/errors)
env_logger::init();
// Creating options
let options = ConfigSetupOptions {
pretty: false,
..Default::default()
};
// Creating a new config struct with our data struct (it can also guess the file extension)
let result = Config::from_options(
"./config/myconfig",
options,
MyData::default()
);
// Error matching
let mut config = match result {
Ok(cfg) => {
cfg
}
Err(error) => {
match error {
// Failed parsing the config
ConfigError::DataParseError(parse_err) => {
match parse_err {
DataParseError::Serialize(format) =>
panic!("Failed to serialize format {format}!"),
DataParseError::Deserialize(format, _string) =>
panic!("Failed to deserialize format {format}!")
}
}
_ => panic!("Other error!")
}
}
};
// Read/writing to the data
println!("I am ${} in debt", config.data.student_debt);
config.data.student_debt = i32::MAX;
println!("Oh no, i am now ${} in debt!!", config.data.student_debt);
// Saving it back to the disk
config.save().unwrap();
}