-
-
Save rust-play/ad8976487fbeaad3ef3f5ebb107007e3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
use std::fs; | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
// Create a dummy config.toml file for demonstration purposes | |
fs::write("config.toml", "key = \"value\"\nother_key = 123\nanother_string_key = \"hello world\"")?; | |
let contents = fs::read_to_string("config.toml")?; | |
println!("Contents of config.toml:\n{}", contents); | |
println!("------------------------------------"); | |
// Variables to store the extracted values | |
let mut key_value: Option<String> = None; | |
let mut other_key_value: Option<i32> = None; | |
let mut another_string_key_value: Option<String> = None; | |
// Iterate over each line in the contents | |
for line in contents.lines() { | |
// Trim whitespace from the line | |
let trimmed_line = line.trim(); | |
// Skip empty lines or lines that might be comments (starting with #) | |
if trimmed_line.is_empty() || trimmed_line.starts_with('#') { | |
continue; | |
} | |
// Split the line by the first '=' | |
if let Some((key_part, value_part)) = trimmed_line.split_once('=') { | |
let key = key_part.trim(); | |
let raw_value = value_part.trim(); | |
match key { | |
"key" => { | |
// Remove quotes from the string value | |
let value = raw_value.trim_matches('"'); | |
key_value = Some(value.to_string()); | |
} | |
"other_key" => { | |
// Parse the string to an integer | |
other_key_value = Some(raw_value.parse::<i32>()?); | |
} | |
"another_string_key" => { | |
// Remove quotes from the string value | |
let value = raw_value.trim_matches('"'); | |
another_string_key_value = Some(value.to_string()); | |
} | |
_ => { | |
// Handle unknown keys if necessary | |
eprintln!("Warning: Unknown key found in config: {}", key); | |
} | |
} | |
} | |
} | |
// Now, access the assigned values | |
println!("Extracted Values:"); | |
if let Some(val) = key_value { | |
println!("key = \"{}\"", val); | |
} else { | |
println!("key not found or could not be parsed."); | |
} | |
if let Some(val) = other_key_value { | |
println!("other_key = {}", val); | |
} else { | |
println!("other_key not found or could not be parsed."); | |
} | |
if let Some(val) = another_string_key_value { | |
println!("another_string_key = \"{}\"", val); | |
} else { | |
println!("another_string_key not found or could not be parsed."); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment