A small parser can convert raw text into structured parts while rejecting incomplete input.

Program

Play the program to choose an input string and parse it into a key/value pair.

input
key_value_pair_parser.rs
Replay: real traced execution (multi-file project)
fn main() {
    let input = "mode=debug";
    match parse_pair(input) {
        Some((key, value)) => println!("{key}:{value}"),
        None => println!("invalid"),
    }
}

fn parse_pair(input: &str) -> Option<(&str, &str)> {
    let (key, value) = input.split_once('=')?;
    if key.is_empty() || value.is_empty() {
        None
    } else {
        Some((key, value))
    }
}
fn main() {
    let input = "limit=10";
    match parse_pair(input) {
        Some((key, value)) => println!("{key}:{value}"),
        None => println!("invalid"),
    }
}

fn parse_pair(input: &str) -> Option<(&str, &str)> {
    let (key, value) = input.split_once('=')?;
    if key.is_empty() || value.is_empty() {
        None
    } else {
        Some((key, value))
    }
}
fn main() {
    let input = "broken";
    match parse_pair(input) {
        Some((key, value)) => println!("{key}:{value}"),
        None => println!("invalid"),
    }
}

fn parse_pair(input: &str) -> Option<(&str, &str)> {
    let (key, value) = input.split_once('=')?;
    if key.is_empty() || value.is_empty() {
        None
    } else {
        Some((key, value))
    }
}
  1. input ← "mode=debug"

    1fn main() {2    let inpu→ "mode=debug"t = "mode=debug"; //@input="mode=debug", "limit=10", "broken"3    match parse_pair(input) {
  2. else

    12        None13    } else {14        Some((ke"mode"y, valu"debug"e))15    }16}
  1. input ← "limit=10"

    1fn main() {2    let inpu→ "limit=10"t = "limit=10";3    match parse_pair(input) {
  2. else

    12        None13    } else {14        Some((ke"limit"y, valu"10"e))15    }16}
  1. input ← "broken"

    1fn main() {2    let inpu→ "broken"t = "broken";3    match parse_pair(input) {
split_once `split_once('=')` separates the first key/value delimiter if it exists.
Option `?` returns `None` immediately when the delimiter is missing.
validation The parser rejects empty keys or values before returning structured data.