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 variableresultand assigns it the result of thesome_function()call.match result {- This line starts amatchblock which is used to match the result of thesome_function()call.Ok(value) => println!("Got a value: {}", value),- This line matches theOkvariant of theresultvariable and prints the value.Err(err) => match err.kind() {- This line matches theErrvariant of theresultvariable and starts amatchblock to match the type of error.ErrorKind::NotFound => println!("Not found"),- This line matches theErrorKind::NotFoundvariant and prints the message "Not found".ErrorKind::PermissionDenied => println!("Permission denied"),- This line matches theErrorKind::PermissionDeniedvariant 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 use binary regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
- How to use regex captures in Rust?
- How to print a Rust HashMap?
- How to sort the keys in a Rust HashMap?
- Generator example in Rust
See more codes...