rustHow to get error message in Rust
Rust provides a number of ways to get error messages. The most common way is to use the Result
type. Result
is an enum that can either be Ok
or Err
. If the operation is successful, Ok
is returned, otherwise Err
is returned with an error message.
Code example:
let result = some_function();
match result {
Ok(value) => println!("Success: {}", value),
Err(err) => println!("Error: {}", err),
}
Output
Success: some_value
Explanation:
- The
some_function()
function is called and the result is stored in theresult
variable. - The
match
statement is used to check the value ofresult
. - If
result
isOk
, theprintln!
macro is used to print the value ofvalue
. - If
result
isErr
, theprintln!
macro is used to print the error message stored inerr
.
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...