Result Enum in Rust Tutorial

beginner
16 min

Result Enum in Rust Tutorial

Welcome to our comprehensive guide on Result Enum in Rust! šŸŽÆ

Result Enum is a powerful feature in Rust that helps manage errors and success cases in a functional and type-safe manner. This tutorial is designed for beginners and intermediates, so let's dive in!

What is Result Enum?

Result Enum is a compound type that represents two possible states: success or error. It is used to return values from functions that might fail and provide a way to handle these failures elegantly.

šŸ“ Note: Result Enum follows the pattern Result<T, E>, where T is the type of data returned on success, and E is the type of error that might occur.

Creating a Custom Result Enum

Let's create a simple custom Result Enum to handle the outcome of a hypothetical function get_user_data().

rust
enum Result { Ok(User), Err(String), }

In the above code, Result is our custom Result Enum, and it can either contain a User (on success) or a String (representing an error message) (on failure).

Using the Result Enum

Now, let's use our custom Result Enum in a function:

rust
fn get_user_data(user_id: i32) -> Result { match user_id { 1 => Result::Ok(User { name: "Alice".to_string() }), _ => Result::Err(String::from("User not found")), } }

In the above code, we define a function get_user_data() that takes a user_id and returns a Result. Depending on the user_id, we either return a successful User or an error message.

Handling the Result

To handle the Result, we can use pattern matching:

rust
fn main() { let result = get_user_data(1); match result { Result::Ok(user) => println!("User found: {:?}", user), Result::Err(err) => println!("Error: {}", err), } }

In the above code, we call the get_user_data() function and pattern match the Result to handle success and error cases.

Quiz

Quick Quiz
Question 1 of 1

What is the type of a Result Enum in Rust?

Stay tuned for more Rust tutorials on CodeYourCraft! šŸ’” Pro Tip: Keep practicing with custom Result Enums and exploring their use in real-world projects! āœ…

Happy coding! 😊