Parse Config Lines With Match Arms
Drive a tiny config parser with match arms, one branch per line shape — comments, section headers, key=value pairs — and report unknown keys as warnings.
Code
#[derive(Debug, Default)]
struct Config {
host: String,
port: u16,
verbose: bool,
}
// match 驱动的逐行解析:每个分支(arm)处理一类行
fn parse_line(line: &str, cfg: &mut Config) -> Option<String> {
let line = line.trim();
match line {
_ if line.is_empty() || line.starts_with('#') => None,
_ if line.starts_with('[') => None, // 段头:本例单段,忽略
_ => {
let (key, value) = line.split_once('=')?;
match key.trim() {
"host" => cfg.host = value.trim().to_string(),
"port" => match value.trim().parse::<u16>() {
Ok(p) => cfg.port = p,
Err(_) => return Some(format!("bad port {value:?}")),
},
"verbose" => cfg.verbose = value.trim() == "true",
other => return Some(format!("unknown key {other}")),
}
None
}
}
}
fn main() {
let text = "# app config\nhost = localhost\n\nport = 8080\nverbose = true\ntimeout = 30\n";
let mut cfg = Config::default();
for line in text.lines() {
if let Some(warn) = parse_line(line, &mut cfg) {
println!("warn: {warn}");
}
}
println!("{cfg:?}");
}How the snippet works
Structurally, expect the functions parse_line and main and nothing else.
Repetition is confined to for line in text.lines() — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Applying it
The primary signature is fn parse_line(line: &str, cfg: &mut Config) -> Option<String>
Look for the warn: prefixes when the file runs; they tie each line to its step.
The sequence parse_line lives in main; running the file triggers it.
Statements that matter
"port" => match value.trim().parse::<u16>() {
Ok(p) => cfg.port = p,
Err(_) => return Some(format!("bad port {value:?}")),
},
if let Some(warn) = parse_line(line, &mut cfg) {
println!("warn: {warn}");
}
let (key, value) = line.split_once('=')?;
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Parse Config Lines With Match Arms print when run?
- Run it as a complete program — the output lines carry labels such as `warn:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.