rustHow to wrap error in Rust
Error wrapping in Rust is a way to handle errors in a more organized and structured way. It allows you to create custom error types that can be used to represent different types of errors. This makes it easier to debug and handle errors in your code.
To wrap an error in Rust, you can use the Result type. This type is used to represent the result of a computation that may either succeed or fail. It has two variants, Ok and Err, which represent the success and failure cases respectively.
Code example:
fn divide(x: i32, y: i32) -> Result<i32, String> {
if y == 0 {
return Err(String::from("Cannot divide by zero"));
}
Ok(x / y)
}
let result = divide(10, 0);
match result {
Ok(val) => println!("Result: {}", val),
Err(err) => println!("Error: {}", err),
}
Output
Error: Cannot divide by zero
Explanation:
-
fn divide(x: i32, y: i32) -> Result<i32, String>: This is the function signature for thedividefunction. It takes twoi32parameters and returns aResulttype with ani32for the success case and aStringfor the failure case. -
if y == 0 { return Err(String::from("Cannot divide by zero")); }: This is a conditional statement that checks if the second parameter is equal to zero. If it is, it returns anErrvariant with an error message. -
Ok(x / y): This is the success case for thedividefunction. It returns anOkvariant with the result of the division. -
let result = divide(10, 0);: This is how we call thedividefunction and store the result in a variable. -
match result { Ok(val) => println!("Result: {}", val), Err(err) => println!("Error: {}", err), }: This is amatchexpression that is used to handle the result of thedividefunction. If the result is anOkvariant, it prints the result. If the result is anErrvariant, it prints the error message.
Helpful links:
More of Rust
- How to use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...