iT邦幫忙

2023 iThome 鐵人賽

DAY 15
0

也有英文版文章
Also this tutorial has been written in English
Check out my Medium

Rust的中文翻譯以參考這份檔案為主.


目錄

  • 結果(Result) Part I

結果(Result) Part I

語法(Syntax)

Result<T, E>

是用來回傳&傳播錯誤(Propagate)的型別

enum Result<T, E> {
   Ok(T),
   Err(E),
}

底線underscore (_)

  • 用來代表任何東西。

Example 01

請注意get_choice(input: &str)函式。


#[derive(Debug)]
enum MenuChoice {
    MainMenu,
    Start,
    Quit,
}

fn get_choice(input: &str) -> Result<MenuChoice, String> {
    match input {
        "mainmenu" => Ok(MenuChoice::MainMenu),
        "start" => Ok(MenuChoice::Start),
        "quit" => Ok(MenuChoice::Quit),
        _ => Err("menu choice not found".to_owned()),
    }
}

fn print_choice(choice: &MenuChoice) {
    println!("choice = {:?}", choice);
}
fn main() {
    let choice: Result<MenuChoice, _> = get_choice("mainmenu");
    match choice {
        Ok(inner_choice) => print_choice(&inner_choice),
        Err(e) => println!("error = {:?}", e),
    }
}
/*
choice = MainMenu
*/

Example 02 - 接續Example 01

What if I set it to something not in the enum MenuChoice
如果設成不在enum MenuChoice裡的東西...


let choice: Result<MenuChoice, _> = get_choice("leave");
    match choice {
        Ok(inner_choice) => print_choice(&inner_choice),
        Err(e) => println!("error = {:?}", e),
    }

/*
error = "menu choice not found"
*/

Example 03 - Ok(())


fn pick_choice(input: &str) -> Result<(), String> {
    let choice: MenuChoice = get_choice(input)?;
    print_choice(&choice);
    Ok(()) /* everyhting is fine */
}

fn main() {
    let choice = pick_choice("start");
    println!("choice value = {:?}", choice);
}

/*
choice = Start
choice value = Ok(())
*/

Example 04

試試看一些例外(exception)

fn pick_choice(input: &str) -> Result<(), String> {
    let choice: MenuChoice = get_choice(input)?;
    print_choice(&choice);
    Ok(()) /* everyhting is fine */
}

fn main() {
    let choice = pick_choice("something");
    println!("choice value = {:?}", choice);
}

/*
choice value = Err("menu choice not found")
*/

Example 01 - 04完整程式碼

#[derive(Debug)]
enum MenuChoice {
    MainMenu,
    Start,
    Quit,
}

fn get_choice(input: &str) -> Result<MenuChoice, String> {
    match input {
        "mainmenu" => Ok(MenuChoice::MainMenu),
        "start" => Ok(MenuChoice::Start),
        "quit" => Ok(MenuChoice::Quit),
        _ => Err("menu choice not found".to_owned()),
    }
}

fn print_choice(choice: &MenuChoice) {
    println!("choice = {:?}", choice);
}

fn pick_choice(input: &str) -> Result<(), String> {
    let choice: MenuChoice = get_choice(input)?;
    print_choice(&choice);
    Ok(()) /* everyhting is fine */
}

fn main() {
    let choice = pick_choice("something");
    println!("choice value = {:?}", choice);
}

Example 05 - impl

什麼是impl | Rust官方文件

  • 可以定義與你的型別有關的函式
  • 以此例來說,impl的區塊都和stuct Adult有關

#[derive(Debug)]
struct Adult {
    age: u8,
    name: String,
}

impl Adult {
    fn new(age: u8, name: &str) -> Result<Self, &str> {
        if age >= 21 {
            Ok(Self {
                age,
                name: name.to_owned(),
            })
        } else {
            Err("Age must be at least 21")
        }
    }
}

fn main() {
    let child = Adult::new(15, "Alice");
    let adult = Adult::new(34, "Bob");

    match child {
        Ok(child) => println!("{} is {} years old.", child.name, child.age),
        Err(e) => println!("{e}"),
    }
    match adult {
        Ok(adult) => println!("{} is {} years old.", adult.name, adult.age),
        Err(e) => println!("{e}"),
    }
}
/*
Age must be at least 21
Bob is 34 years old.
*/


參考資料 Reference

Nice 教學影片


上一篇
Day 14 - 選項(Option)
系列文
Let's go Rusty. 從0開始了解Rust.15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言