]> git.cworth.org Git - rust-learning/commitdiff
Parse the json file and deserialize it into a struct
authorCarl Worth <cworth@cworth.org>
Tue, 10 Mar 2026 02:36:37 +0000 (19:36 -0700)
committerCarl Worth <cworth@cworth.org>
Thu, 12 Mar 2026 04:14:55 +0000 (21:14 -0700)
Where the struct only has a 'name' field so far.

This commit shows a few new things in rust that we haven't seen
previously:

* The "mod config" to depend on a module contained in config.rs

* The ? operator ("try operator") which unwraps a Result if it is_ok,
  and insteadd returns an error if it is not.

* Dependencies on rust packages, (serde_json, and serde with the
  "derive" feature") used for the JSON parsing and deserializing.

* The derive attribute (spelled "#[derive(...)]" used to automatically
  create implementations of the Debug and Deserialize traits for our
  struct. Debug isn't used here, but could be used by passing a
  ConfigFile value to println! or format! macros using a "{:?}" format
  specifier.

* A closure accepting a single parameter: |e| { ... }

Cargo.toml
src/config.rs [new file with mode: 0644]
src/main.rs

index d6ce7ac127adb5d44c2d52ff9ad229a4c31956ab..c2fd62edcac5188ad1b2198d0c38ed339299912a 100644 (file)
@@ -4,3 +4,5 @@ version = "0.1.0"
 edition = "2024"
 
 [dependencies]
+serde = { version = "1", features = ["derive"]}
+serde_json = "1"
diff --git a/src/config.rs b/src/config.rs
new file mode 100644 (file)
index 0000000..8df2cb7
--- /dev/null
@@ -0,0 +1,13 @@
+use serde::Deserialize;
+use std::path::Path;
+
+#[derive(Debug, Deserialize)]
+pub struct ConfigFile {
+    pub name: String,
+}
+
+pub fn load_config(path: &Path) -> Result<ConfigFile, Box<dyn std::error::Error>> {
+    let contents = std::fs::read_to_string(path)?;
+    let config: ConfigFile = serde_json::from_str(&contents)?;
+    Ok(config)
+}
index 404dde8a9d07cbb061065322b0375781bea439db..7154081ccc431f38a75bc9beda5b1867c834aa2e 100644 (file)
@@ -1,3 +1,5 @@
+mod config;
+
 use std::error::Error;
 
 fn main() -> Result<(), Box<dyn Error>> {
@@ -6,5 +8,13 @@ fn main() -> Result<(), Box<dyn Error>> {
         return Err(format!("Usage: {} <race-config.json>", args[0]).into());
     }
 
+    let config_path = std::path::Path::new(&args[1]);
+    let config = config::load_config(config_path).unwrap_or_else(|e| {
+        eprintln!("Error loading config file {}: {}", args[1], e);
+        std::process::exit(1);
+    });
+
+    eprintln!("Race: {}", config.name);
+
     Ok(())
 }