Today I experimented with the subject of error handling. One of several ways in Rust is the Result type.
This is an enum that either contains a value for the success case or an error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
use std::string::String;
#[derive(Debug)]
struct Person {
name: String,
age: i32,
}
impl Person {
fn hello(&self) -> Result<String, &str>{
if self.name != "" {
let ret = format!("{} is {} years old.", self.name, self.age);
Ok(ret)
} else {
Err("No name given")
}
}
}
fn main() {
let bob = Person {
name: String::from("Bob"),
age: 32,
};
let res = bob.hello().unwrap(); // will consume the Ok value or panic in case of error
println!("{:?}", res);
let mary = Person {
name: String::from(""),
age: 30,
};
let res1 = mary.hello().unwrap(); // will consume the Ok value or panic in case of error
println!("{:?}", res1);
}
|
By appending the method unwrap() the returned Result type is unpacked. In the event of an error, unwrap() leads to panic.
The output looks like this:
1
2
3
4
5
6
7
8
9
|
Standard Error:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.05s
Running `target/debug/playground`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: "No name given"', src/main.rs:33:29
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Standard Output:
"Bob is 32 years old."
|
I think that’s just the beginning. Using the method unwrap() is quick and easy, but usually you would not want your program to quit with a panic on error.