Parsing Strings to Numbers
Part of the Logic & Flow section of Coddy's Rust journey — lesson 47 of 66.
One of the most common real-world applications of Result is converting strings to numbers. In Rust, this is done using the .parse() method, which demonstrates perfectly why Result exists - because parsing can fail.
The .parse() method attempts to convert a string into a number, but not every string represents a valid number. For example, "42" can be parsed into the number 42, but "hello" cannot be converted to any number:
let valid_number = "42";
let invalid_number = "hello";
let result1: Result = valid_number.parse();
let result2: Result = invalid_number.parse();When parsing succeeds, .parse() returns Ok(number) containing the converted value. When it fails, it returns Err(error) with information about why the parsing failed. This forces you to handle both possibilities explicitly, preventing your program from crashing on invalid input.
You can handle the parsing result using any of the Result techniques you've learned - match for explicit handling, unwrap() if you're certain it will succeed, or the ? operator to propagate errors.
Challenge
EasyWrite a function parse_to_integer that takes a string input and returns the parsed integer value. If the string cannot be parsed into a valid integer, return 0 as a default value.
Use the .parse() method to convert the string to an i32, and handle the Result appropriately to provide a safe return value.
Parameters:
input(String): The string to parse into an integer
Returns: The parsed integer if successful, or 0 if parsing fails (i32)
Cheat sheet
The .parse() method converts a string into a number and returns a Result type because parsing can fail:
let valid_number = "42";
let invalid_number = "hello";
let result1: Result<i32, _> = valid_number.parse();
let result2: Result<i32, _> = invalid_number.parse();When parsing succeeds, .parse() returns Ok(number). When it fails, it returns Err(error).
You can handle parsing results using match, unwrap(), the ? operator, or unwrap_or() to provide a default value on failure.
Try it yourself
fn parse_to_integer(input: String) -> i32 {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together