0
0
Rustprogramming~15 mins

Handling errors with match in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling errors with match
📖 Scenario: You are writing a small Rust program that reads a number from a string and handles possible errors gracefully.
🎯 Goal: Build a Rust program that converts a string to a number using parse() and uses match to handle success and error cases.
📋 What You'll Learn
Create a string variable with a number value
Create a variable to hold the parsed result using parse()
Use match to handle Ok and Err cases
Print the parsed number if successful or an error message if parsing fails
💡 Why This Matters
🌍 Real World
Parsing user input or data from files often requires handling errors to avoid program crashes.
💼 Career
Understanding error handling with <code>match</code> is essential for writing safe and reliable Rust programs.
Progress0 / 4 steps
1
Create a string with a number
Create a variable called number_str and set it to the string "42".
Rust
Hint

Use let to create the variable and put the number inside quotes.

2
Parse the string to a number
Create a variable called parsed_number and set it to the result of calling number_str.parse::().
Rust
Hint

Use parse::() to convert the string to a 32-bit integer.

3
Use match to handle parsing result
Use match parsed_number with arms for Ok(num) and Err(e). Inside Ok(num), create a variable number equal to num. Inside Err(e), create a variable error_message equal to e.to_string().
Rust
Hint

Use match to check if parsing was successful or not.

4
Print the result or error message
Inside the Ok(num) arm, add println!("Parsed number: {}", num);. Inside the Err(e) arm, add println!("Failed to parse number: {}", e);.
Rust
Hint

Use println! to show the number or error message.