Parse and format text
Quick answer
Parsing converts text to a typed value; formatting converts values into text for display or storage. Neither conversion should assume that arbitrary user input is valid.
Handle invalid input
text.parse::<i32>() attempts to parse a signed integer. The angle brackets specify the target type. It returns Result, whose Ok variant contains a value and Err contains a failure; the error-handling chapter explains this type fully. A match can select either branch. trim() borrows the text without leading and trailing whitespace. Formatting with format! returns an owned String.
fn main() { let input = " 24 "; match input.trim().parse::<i32>() { Ok(n) => println!("{}", format!("count={n}")), Err(_) => println!("invalid number"), }}Expected stdout (not executed):
count=24The spaces are trimmed before parsing; formatting adds a label.
fn main() { match "4x".parse::<i32>() { Ok(n) => println!("{n}"), Err(_) => println!("invalid number"), }}Expected stdout (not executed):
invalid numberThe invalid input follows a normal error branch without panicking.
Common mistake
Do not assume parsing accepts every string or trims whitespace automatically.
Try it yourself
Try inputs "-12", " 8 " and "abc"; display success or an understandable error.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Parse and format text — practice quiz
Choose one answer per question, then review the explanation.
What does `" 12 ".trim()` produce?
What does `"-8".parse::<i32>()` return?
What is a useful way to handle invalid numeric text at this point in the curriculum?