0
0
Rustprogramming~15 mins

Using unwrap and expect in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Using unwrap and expect
📖 Scenario: Imagine you are writing a small Rust program that reads a user's age from a string and wants to convert it to a number. Sometimes the string might not be a valid number, so you need to handle that carefully.
🎯 Goal: You will learn how to use unwrap and expect to handle the result of converting a string to a number in Rust. This will help you understand how to deal with possible errors in a simple way.
📋 What You'll Learn
Create a string variable with a number value
Create a string variable with a non-number value
Use unwrap to convert the number string to an integer
Use expect to convert the non-number string to an integer with a custom error message
Print both results
💡 Why This Matters
🌍 Real World
Parsing user input or data from files often requires converting strings to numbers. Using <code>unwrap</code> and <code>expect</code> helps quickly handle success or failure in simple programs.
💼 Career
Understanding error handling with <code>unwrap</code> and <code>expect</code> is essential for Rust developers to write safe and clear code, especially when dealing with input/output and data parsing.
Progress0 / 4 steps
1
Create string variables with number and non-number values
Create a string variable called number_str with the value "42" and another string variable called not_number_str with the value "abc".
Rust
Hint

Use let to create variables and assign string values with double quotes.

2
Parse the number string using unwrap
Create a variable called number and set it to the result of parsing number_str to an i32 using parse() and then call unwrap() on it.
Rust
Hint

Use parse() to convert the string to a number and unwrap() to get the value or panic if it fails.

3
Parse the non-number string using expect with a message
Create a variable called not_number and set it to the result of parsing not_number_str to an i32 using parse() and then call expect("Failed to parse not_number_str") on it.
Rust
Hint

Use expect() to provide a custom error message if parsing fails.

4
Print the parsed values
Use println! to print number and not_number variables on separate lines.
Rust
Hint

Use println!("{}", variable); to print variables. The program will panic on the second print because of the invalid parse.