Small Programs · 11 min · free with an account

Parsing Values

Lesson preview · about 30%

Parsing crosses from untrusted text into a type with explicit success or failure.

Core idea

Parsing returns Result because input text is not guaranteed to fit the target type.

Start with the idea

parse is generic: the destination type tells it what grammar to use. Because arbitrary text may be invalid, the result is Result rather than a bare value. A type annotation or turbofish such as parse::<i32>() resolves the target type, after which match, ?, or another deliberate policy handles failure.

Text arrives as bytes and characters, not as a trusted number. The call "42".parse::<i32>() asks Rust to interpret it using i32's parsing rules. That operation can fail, so it returns Result<i32, ParseIntError>. The annotation Result<i32, _> in the example gives rustc enough information to infer the error type; the underscore does not mean the error disappears. A successful parse produces Ok(42), while invalid text such as "forty-two" produces Err with diagnostic information.

The match in the example deliberately handles both outcomes. It prints the number on success and the error on failure.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics