Skip to content

Turn Text into a Number with Result

The Course
•
28 min study

People type text, not numbers. Before a planner can add "25" to a total, it has to convert the text, and that conversion can fail: "later" is not a number at all. Option could say "no number", but it could not say why, and a useful error message needs the reason. Result<T, E> is the enum for work that can succeed or fail. Ok(value) holds the result of a success, of type T. Err(error) holds a description of the failure, of type E.

text.parse::<u32>() asks Rust to read text as an unsigned 32-bit integer and returns a Result. Parsing only answers "is this text a valid u32?". Whether the number makes sense for your program is a second question. A match guard, written if condition after a pattern, narrows one arm. If the pattern matches but the guard is false, Rust moves on and tries the remaining arms.

Predict and run

Which input parses successfully but fails the positive-duration rule?

Predict, then run Rust
fn main() {
    for text in [" 25 ", "0", "later"] {
        match text.trim().parse::<u32>() {
            Ok(minutes) if minutes > 0 => println!("Accepted {minutes}"),
            Ok(_) => println!("Duration must be positive"),
            Err(_) => println!("Enter a whole number"),
        }
    }
}
Check your prediction
Text
Accepted 25
Duration must be positive
Enter a whole number

"0" is a perfectly good u32, so it reaches an Ok arm, but the guard minutes > 0 rejects it and the next arm, Ok(_), catches it. The underscore means "any value, and I will not use it".

Add "-3" and "2.5" to the inputs. Predict which arm handles each, then run. A u32 has no room for a minus sign or a decimal point, so both fail to parse.

Arm order decides

Arms are tried from top to bottom, so a general pattern placed first hides everything after it. Here the unguarded Ok(_) comes before the guarded arm:

Put the general arm first by mistake Rust
fn main() {
    for text in ["25", "0"] {
        match text.parse::<u32>() {
            Ok(_) => println!("Duration must be positive"),
            Ok(minutes) if minutes > 0 => println!("Accepted {minutes}"),
            Err(_) => println!("Enter a whole number"),
        }
    }
}
Text
Duration must be positive
Duration must be positive

Every valid number now gets the rejection message, and the Accepted arm can never run. The program still compiles; the compiler only prints warning: unreachable pattern. Read warnings: this one points straight at the bug. Put specific patterns and guarded arms before the general ones.

Read the error and return your own

The Err arm can name the error instead of ignoring it. A parse error prints a short explanation, which shows why trimming matters: the space in " 25" is not a digit.

Print why parsing failed Rust
fn main() {
    for text in [" 25", "", "99999999999"] {
        match text.parse::<u32>() {
            Ok(minutes) => println!("{minutes}"),
            Err(error) => println!("{text:?}: {error}"),
        }
    }
}
Text
" 25": invalid digit found in string
"": cannot parse integer from empty string
"99999999999": number too large to fit in target type

These messages are written for programmers. For the people using your program, it is better to decide the messages yourself. A function can return Result too: here the error type is &'static str, a fixed piece of text, and each early return Err(...) leaves the function with a reason.

Return a Result with your own messages Rust
fn parse_minutes(text: &str) -> Result<u32, &'static str> {
    let minutes = match text.trim().parse::<u32>() {
        Ok(value) => value,
        Err(_) => return Err("enter a whole number"),
    };
    if minutes == 0 {
        return Err("duration must be positive");
    }
    Ok(minutes)
}

fn main() {
    for text in ["45", "0", "soon"] {
        match parse_minutes(text) {
            Ok(minutes) => println!("{minutes} min"),
            Err(message) => println!("Rejected {text}: {message}"),
        }
    }
}
Text
45 min
Rejected 0: duration must be positive
Rejected soon: enter a whole number

This is the shape of the study planner's add_line on Day 7: check each rule in turn, leave early with a message, and return Ok only at the end.

Two questions, two branches

Keep "is it a number?" and "is it allowed?" as separate branches with separate messages. "Enter a whole number" and "Use 1–240 minutes" ask the user to fix different things.

Practice

Exercise

Your turn

Accept page counts from 1 through 1000 inclusive. For ["1000", "1001", "zero"], print Pages: 1000, Out of range and Invalid number, one per line. Try 0 and 1 too.

Your working space Rust
fn main() {
    for text in ["1000", "1001", "zero"] {
        println!("{text}");
    }
}
Hint 1: the idea

Check the allowed range after parsing. Keep the error branch for text that fails to parse.

Hint 2: a first step

Guard the first Ok arm with pages >= 1 && pages <= 1000. The && requires both comparisons to be true.

Worked solution
Run the solution Rust
fn main() {
    for text in ["1000", "1001", "zero"] {
        match text.parse::<u32>() {
            Ok(pages) if pages >= 1 && pages <= 1000 => println!("Pages: {pages}"),
            Ok(_) => println!("Out of range"),
            Err(_) => println!("Invalid number"),
        }
    }
}
Text
Pages: 1000
Out of range
Invalid number

1001 is a valid u32, so it parses; it fails the rule for this program and reaches the second Ok arm. With 0 you get Out of range and with 1 you get Pages: 1, so both ends of the range behave. Next you will read the text from the user instead of writing it in the program.

Was this article helpful?

Your response is saved on this device.