Parse Key-Value Pairs With split_once
split_once cuts at the first delimiter and returns Option of two borrowed slices, while rsplit_once cuts from the right for URLs and paths.
Code
fn main() {
// split_once 只在第一个分隔符处切一刀,返回 Option<(前, 后)>
let lines = [
"timeout=30s",
"retries=5",
"proxy=http://10.0.0.1:8080",
"novalue-here",
];
for line in lines {
match line.split_once('=') {
Some((key, value)) => println!("{key} -> {value:?}"),
None => println!("{line:?} -> skipped: no '='"),
}
}
// URL 里带 '://':split_once 会切错位置,rsplit_once 从右侧切才保得住 scheme
let target = "https://api.example.com/v2/users?limit=5";
match target.rsplit_once("://") {
Some((scheme, rest)) => println!("scheme={scheme} rest={rest}"),
None => println!("no scheme"),
}
}Inside the snippet
Parse Key-Value Pairs With split_once keeps everything in the function main.
Repetition is confined to for line in 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.
Putting it to use
The demo output is labeled (scheme=, no scheme); each label names the call that printed it.
Core lines
match target.rsplit_once("://") {
Some((scheme, rest)) => println!("scheme={scheme} rest={rest}"),
None => println!("no scheme"),
}
match line.split_once('=') {
Some((key, value)) => println!("{key} -> {value:?}"),
None => println!("{line:?} -> skipped: no '='"),
}
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.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.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Parse Key-Value Pairs With split_once print when run?
- Execute the whole file; each printed line is prefixed with a label like `scheme=`, `no scheme`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.