iT邦幫忙

2023 iThome 鐵人賽

DAY 14
0

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

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


目錄

  • 選項(Option)

選項(Option)

  • 選項(Option):一個型別也可能是兩種東西的其中一個(A type that may be one of two things)

  • 一個指定的型別中的一些Some檔案(Some data of a specified type)

  • Nothing

  • 選項(Option)被用在以下情境:

  • 當檔案不在被需要或已經不能被使用了(Used in scenarios where data may not be required or is unavailable)

什麼是Some | StackOverflow
Option | Rust官方文件

Example 01 -

struct Customer {
    age: Option<i32>,
    email: String,
}
fn main() {
    let alice = Customer {
        age: Some(22),
        email: "alice@example.com".to_owned(),
    };

    let Lauren = Customer {
        age: None,
        email: "lauren@example.com".to_owned(),
    };

    match alice.age {
        Some(age) => println!("Customer is {:?} years old.", age),
        None => println!("Customer age is not provided."),
    }
}

/*
Customer is 22 years old.
*/

Example 02

struct GroceryItem {
    name: String,
    qty: i31,
}
fn find_quantity(name: &str) -> Option<i32> {
    let groceries = vec![
        GroceryItem {
            name: "bananas".to_owned(),
            qty: 4,
        },
        GroceryItem {
            name: "Avocado".to_owned(),
            qty: 3,
        },
        GroceryItem {
            name: "Lemon".to_owned(),
            qty: 7,
        },
    ];
    for item in groceries {
        if item.name == name {
            return Some(item.qty);
        }
    }
    None
}

Example 03

struct Survey {
    q1: Option<i32>,
    q2: Option<bool>,
    q3: Option<String>,
}

fn main() {
    let response = Survey {
        q1: None,
        q2: Some(true),
        q3: Some("A".to_owned()),
    };

    match response.q1 {
        Some(ans) => println!("q1: {:?}", ans),
        None => println!("q1: no response"),
    }
    match response.q2 {
        Some(ans) => println!("q2: {:?}", ans),
        None => println!("q2: no response"),
    }
    match response.q3 {
        Some(ans) => println!("q3: {:?}", ans),
        None => println!("q3: no response"),
    }
}

/*
q1: no response
q2: true
q3: "A"
*/

接下來,試著改變一些檔案(data)

Example 04

let response = Survey {
        q1: Some(12),
        q2: Some(false),
        q3: Some("A".to_owned()),
    };

/*
q1: 12
q2: false
q3: "A"
*/

將值都設為None

Example 05


let response = Survey {
        q1: None,
        q2: None,
        q3: None,
    };

Example 06

struct Student {
    name: String,
    locker: Option<i32>,
}

fn main() {
    let alice: Student = Student {
        name: "Alice".to_owned(),
        locker: Some(3),
    };
    println!("Student: {:?}", alice.name);
    match alice.locker {
        Some(num) => println!("Locker number: {:?}", num),
        None => println!("No locker assigned."),
    }
}

/*
student: "Alice"
Locker number: 3
*/

參考資料 Reference

Nice 教學影片


上一篇
Day 13 - 型別標記(Type Annotation) & 進階Match(Advanced Match)
下一篇
Day 15 - 結果(Result) Part I
系列文
Let's go Rusty. 從0開始了解Rust.15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言