1.8 KiB
1.8 KiB
title, date, draft, series, tags
title | date | draft | series | tags | |||
---|---|---|---|---|---|---|---|
Part 2: Result Type and error handling | 2020-09-19 | false |
|
|
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.
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:
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.