From 1bc098d3437a50dc0b2570e05aa7dc8653469a08 Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Mon, 9 Mar 2026 19:36:37 -0700 Subject: [PATCH] Parse the json file and deserialize it into a struct 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 | 2 ++ src/config.rs | 13 +++++++++++++ src/main.rs | 10 ++++++++++ 3 files changed, 25 insertions(+) create mode 100644 src/config.rs diff --git a/Cargo.toml b/Cargo.toml index d6ce7ac..c2fd62e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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 index 0000000..8df2cb7 --- /dev/null +++ b/src/config.rs @@ -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> { + let contents = std::fs::read_to_string(path)?; + let config: ConfigFile = serde_json::from_str(&contents)?; + Ok(config) +} diff --git a/src/main.rs b/src/main.rs index 404dde8..7154081 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +mod config; + use std::error::Error; fn main() -> Result<(), Box> { @@ -6,5 +8,13 @@ fn main() -> Result<(), Box> { return Err(format!("Usage: {} ", 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(()) } -- 2.45.2