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.

RustConfig Management

Code

rustsnippet
23 lines
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

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`.