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!
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.
Let's create a simple custom Result Enum to handle the outcome of a hypothetical function get_user_data().
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).
Now, let's use our custom Result Enum in a function:
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.
To handle the Result, we can use pattern matching:
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.
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! š