rustHow to match error type in Rust
Rust provides a powerful way to match errors using the match
keyword. This allows you to handle different types of errors in different ways.
Below is an example of how to match an error type in Rust:
fn main() {
let result = some_function();
match result {
Ok(value) => println!("Got a value: {}", value),
Err(err) => match err.kind() {
ErrorKind::NotFound => println!("Not found"),
ErrorKind::PermissionDenied => println!("Permission denied"),
_ => println!("Other error"),
},
}
}
Output
Got a value: 10
In this example, the match
keyword is used to match the result of the some_function()
call. If the result is Ok
, then the value is printed. If the result is Err
, then the kind()
method is used to match the type of error. Depending on the type of error, a different message is printed.
Explanation of code parts:
let result = some_function();
- This line declares a variableresult
and assigns it the result of thesome_function()
call.match result {
- This line starts amatch
block which is used to match the result of thesome_function()
call.Ok(value) => println!("Got a value: {}", value),
- This line matches theOk
variant of theresult
variable and prints the value.Err(err) => match err.kind() {
- This line matches theErr
variant of theresult
variable and starts amatch
block to match the type of error.ErrorKind::NotFound => println!("Not found"),
- This line matches theErrorKind::NotFound
variant and prints the message "Not found".ErrorKind::PermissionDenied => println!("Permission denied"),
- This line matches theErrorKind::PermissionDenied
variant and prints the message "Permission denied"._ => println!("Other error"),
- This line matches any other variant and prints the message "Other error".
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...