0
0
Rustprogramming~30 mins

Result enum in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Success and Errors with the Result Enum in Rust
📖 Scenario: Imagine you are writing a small program that tries to divide two numbers. Sometimes the division might fail if the divisor is zero. Rust's Result enum helps us handle such success or error cases safely.
🎯 Goal: You will create a function that divides two numbers and returns a Result enum. Then you will call this function and handle both success and error cases.
📋 What You'll Learn
Create a function called divide that takes two f64 numbers and returns Result<f64, String>
Return Ok with the division result if the divisor is not zero
Return Err with an error message if the divisor is zero
Call the divide function with example values
Use match to handle both Ok and Err cases and print appropriate messages
💡 Why This Matters
🌍 Real World
Handling success and error cases is common in real-world programs, such as reading files, network requests, or user input validation.
💼 Career
Understanding the <code>Result</code> enum is essential for Rust developers to write robust and error-resistant applications.
Progress0 / 4 steps
1
Create the divide function with Result return type
Write a function called divide that takes two f64 parameters named numerator and denominator. The function should return Result<f64, String>. For now, just return Ok(0.0) to set up the function.
Rust
Hint

Define the function with the correct parameters and return type. Use Ok(0.0) as a placeholder return value.

2
Add logic to check for zero denominator and return Err
Inside the divide function, add an if statement to check if denominator is zero. If it is, return Err with the message "Cannot divide by zero". Otherwise, return Ok with the division result numerator / denominator.
Rust
Hint

Use an if condition to check for zero and return Err. Otherwise, return Ok with the division.

3
Call divide with example values and use match to handle the result
Create two variables: result1 by calling divide(10.0, 2.0) and result2 by calling divide(5.0, 0.0). Then use a match statement on result1 with arms for Ok(value) and Err(message). Print "Result: {value}" for Ok and "Error: {message}" for Err. Repeat the same match for result2.
Rust
Hint

Call the function twice with different values. Use match to print the success or error messages.

4
Print the results of the division attempts
Run the program to print the output of both division attempts. The output should show the successful division result and the error message for division by zero.
Rust
Hint

Run the program and check that it prints the correct success and error messages.