iT邦幫忙

2023 iThome 鐵人賽

DAY 13
0
自我挑戰組

Let's go Rusty. 從0開始了解Rust.系列 第 13

Day 13 - 型別標記(Type Annotation) & 進階Match(Advanced Match)

  • 分享至 

  • xImage
  •  

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

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


目錄

  • 型別標記(Type Annotation)
  • 進階Match(Advanced Match)

型別標記(Type Annotation)

Example 01 - 型別標記(Type Annotation)

基礎

enum Movement {
    Up,
    Down,
    Left,
    Right,
}

fn main() {
    let turn_right: Movement = Movement::Right;
}

Example 02

enum Movement {
    Up,
    Down,
    Left,
    Right,
}

fn main() {
    let turning_direction: Vec<Movement> = vec![
        Movement::Up,
        Movement::Down,
        Movement::Left,
        Movement::Right,
    ];
}


Advanced Match

Example 03

使用struct進行match分類。


struct movie_ticket {
    name: String,
    price: i32,
}

fn main() {
    let a = movie_ticket {
        name: "Spiderverse".to_owned(),
        price: 25,
    };
    match a {
        movie_ticket { price: 50, name } => println!("Movie {:?}", name),
        movie_ticket { price, .. } => println!("Price = {:?}", price),
    }
}
/*
Price = 25
*/

Example 04

使用enum進行match分類。

enum Ticket {
    Backstage(f64, String),
    Standard(f64),
    Vip(f64, String),
}

fn main() {
    let tickets: Vec<Ticket> = vec![
        Ticket::Backstage(50.0, "Alice".to_owned()),
        Ticket::Standard(15.0),
        Ticket::Vip(30.0, "Lauren".to_owned()),
    ];

    for ticket in tickets {
        match ticket {
            Ticket::Backstage(price, holder) => {
                println!("Backstage ticket holder: {:?}, price: {:?}", holder, price);
            }
            Ticket::Standard(price) => println!("Standard ticket price: {:?}", price),
            Ticket::Vip(price, holder) => {
                println!("VIP ticket holder: {:?}, price: {:?}", holder, price);
            }
        }
    }
}

參考資料 Reference

Nice 教學影片


上一篇
Day 12 - 派生屬性(Derive) & 參數和引數的差異(Difference between parameter and argument)
下一篇
Day 14 - 選項(Option)
系列文
Let's go Rusty. 從0開始了解Rust.15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言