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 integerUse
expect to convert the non-number string to an integer with a custom error messagePrint 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