67 lines
1.8 KiB
Markdown
67 lines
1.8 KiB
Markdown
---
|
|
title: "Part 2: Result Type and error handling"
|
|
date: 2020-09-19
|
|
draft: false
|
|
series: ["Starting with rust"]
|
|
tags: ["rust","coding"]
|
|
---
|
|
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.
|
|
|
|
```rust
|
|
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:
|
|
|
|
```rust
|
|
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.
|