Skip to content

Attach a Reason to a Missing Field

The Course
•
25 min study

Many standard library methods answer "is it there?" with an Option. split_once(',') returns Some((before, after)) if the comma exists and None if it does not. BTreeMap::get returns None for a missing key. That is the right answer for the method, which cannot know what a missing comma means to you. Your parser does know: in a row like 7, Rust, a missing comma means the person forgot the separator, and the error should say so.

ok_or(error) makes that translation. It turns Some(value) into Ok(value) and None into Err(error). Once you have a Result, the ? from the previous lesson can return the error from your function. Then keep a second, separate question in mind: a field can be present and still be blank. "7, " has a comma, so split_once succeeds, but the title after it is empty. Checking the trimmed slice separately keeps those two mistakes distinct.

Predict and run

Which input has the delimiter but no title? Which one never gets as far as the trim?

Predict, then run Rust
#[derive(Debug, PartialEq, Eq)]
enum FieldError {
    MissingSeparator,
    EmptyTitle,
}

fn title(line: &str) -> Result<&str, FieldError> {
    let (_, field) = line.split_once(',').ok_or(FieldError::MissingSeparator)?;
    let field = field.trim();
    if field.is_empty() { Err(FieldError::EmptyTitle) } else { Ok(field) }
}

fn main() {
    for line in ["7, Rust ", "7", "7, "] {
        println!("{:?}", title(line));
    }
}
Check your prediction
Text
Ok("Rust")
Err(MissingSeparator)
Err(EmptyTitle)

"7" has no comma, so ok_or produces MissingSeparator and ? returns before the trim. "7, " has a comma; the field is a single space, which trims to an empty slice. The returned &str borrows from line: no new string is created. Now try "7, Rust, revised". Predict which comma split_once uses and what becomes the title before you run it.

Combine several checks in one parser

A real row has more than one part that can go wrong, and each step can turn its own Option or Result into a reason. The steps run in order, and the first failure wins. That order is a design decision: here a row with no comma at all is reported as a missing separator, even if what came before it was not a number.

Parse an ID and a title from one row Rust
#[derive(Debug, PartialEq, Eq)]
enum RowError {
    MissingSeparator,
    BadId,
    EmptyTitle,
}

fn row(line: &str) -> Result<(u32, &str), RowError> {
    let (id, title) = line.split_once(',').ok_or(RowError::MissingSeparator)?;
    let id = id.trim().parse::<u32>().map_err(|_| RowError::BadId)?;
    let title = title.trim();
    if title.is_empty() {
        return Err(RowError::EmptyTitle);
    }
    Ok((id, title))
}

fn main() {
    for line in ["7, Rust Patterns", "seven, Rust", "seven", " 3 ,  "] {
        println!("{line:?} -> {:?}", row(line));
    }
}
Text
"7, Rust Patterns" -> Ok((7, "Rust Patterns"))
"seven, Rust" -> Err(BadId)
"seven" -> Err(MissingSeparator)
" 3 ,  " -> Err(EmptyTitle)

ok_or handles the Option from split_once, and map_err handles the Result from parse; after each one, ? sees a Result with RowError on the error side. The last input parses its ID because the ID is trimmed first, then fails on the empty title. The Day 7 queue uses the same move in finish: self.books.get_mut(&id).ok_or(QueueError::UnknownId)? turns a missing key into a named error in one line.

Why the question mark alone is not enough

It is tempting to write line.split_once(',')? directly. Inside a function that returns Result, that does not compile:

Rust
#[derive(Debug)]
enum FieldError {
    MissingSeparator,
}

fn title(line: &str) -> Result<&str, FieldError> {
    let (_, field) = line.split_once(',')?;
    Ok(field.trim())
}

The message is error[E0277]: the ? operator can only be used on Results, not Options, in a function that returns Result, and the compiler even suggests .ok_or(...)?. The rule is that ? on an Option returns None, which only makes sense when the function itself returns an Option. Rust will not guess which error a None should become, because only you know.

ok_or or ok_or_else

ok_or(error) builds the error value every time, even when the Option is Some. That is free for a plain enum variant like MissingSeparator. If building the error costs something, such as formatting a String, use ok_or_else(|| ...), which runs the closure only on None.

Practice

Exercise

Your turn

Write after_colon(line: &str) -> Result<&str, FieldError> that borrows and trims the text after the first colon. Return NoColon when there is no colon and EmptyValue when the text after it is blank. Assert all three outcomes for "title: Rust ", "title" and "title: ", then print Field checks passed.

Your working space Rust
#[derive(Debug, PartialEq, Eq)]
enum FieldError {
    NoColon,
    EmptyValue,
}

fn main() {
    // Check "title: Rust ", "title", and "title: ".
}
Hint 1: the idea

The Option from splitting only tells you whether the delimiter exists. Whether the value is blank is a second check on the slice you get back.

Hint 2: a first step

Split with line.split_once(':'), convert None using .ok_or(FieldError::NoColon)?, then trim the second half.

Worked solution
Run the solution Rust
#[derive(Debug, PartialEq, Eq)]
enum FieldError {
    NoColon,
    EmptyValue,
}

fn after_colon(line: &str) -> Result<&str, FieldError> {
    let (_, value) = line.split_once(':').ok_or(FieldError::NoColon)?;
    let value = value.trim();
    if value.is_empty() { Err(FieldError::EmptyValue) } else { Ok(value) }
}

fn main() {
    assert_eq!(after_colon("title: Rust "), Ok("Rust"));
    assert_eq!(after_colon("title"), Err(FieldError::NoColon));
    assert_eq!(after_colon("title: "), Err(FieldError::EmptyValue));
    println!("Field checks passed");
}
Text
Field checks passed

The return type needs no lifetime annotation: with one borrowed input, Rust infers that the returned &str borrows from line, as you saw on Day 2. The function never copies the value, so it costs nothing beyond the search for the colon. The next lesson builds a whole command parser from these pieces.

Was this article helpful?

Your response is saved on this device.