iT邦幫忙

2023 iThome 鐵人賽

DAY 9
1
自我挑戰組

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

Day 09 - 記憶體Memory - 所有權(Ownership) & 執行(Implement)

  • 分享至 

  • xImage
  •  

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

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


目錄

  • 所有權(Ownership)
  • 執行(Implement)

記憶體(Memory)

  • 記憶體使用位址和偏移值(addresses & offsets)
  • 位址是永久的,檔案則不盡相同
  • 偏移植可以用來在某些檔案中建立索引(Offsets can be used to "index" into some data)

所有權(Ownership)

  • 記憶體必須在某些方面做好處理,避免記憶體洩漏(leaks)。
  • Rust使用所有權(Ownership)去處理記憶體。
  • 所有人(owner)必須清理記憶體
  • 在程式scope的末端,這會自動發生(This occurs automatically at the end of the scope)
  • 預設行為是"移動記憶體到新的所有人(owner)"
  • 使用&符號去允許程式碼"借用"記憶體(Use an ampersand ( & ) to allow code to "borrow" memory)

✨更多請看Rust檔案 - 所有權

Example 01 - 基本示範

注意兩個範例,第二個有註解,展示兩者差別。

❌ 這個範例會出現錯誤提示

// ❌❌❌
struct GroceryItem {
    quantity: i32,
    id: i32,
}

fn display_quantity(item: GroceryItem) {
    println!("quantity: {:?}", item.quantity);
}

fn display_id(item: GroceryItem) {
    println!("id: {:?}", item.id);
}

fn main() {
    let my_item = GroceryItem {
        quantity: 3,
        id: 99,
    };

    display_quantity(my_item);
    display_id(my_item);
}


https://ithelp.ithome.com.tw/upload/images/20230912/20145149iVTbEwcQ6D.png

✔️ 這個可以運作

// ✔️✔️✔️
struct GroceryItem {
    quantity: i32,
    id: i32,
}

fn display_quantity(item: &GroceryItem) { // Add &
    println!("quantity: {:?}", item.quantity);
}

fn display_id(item: &GroceryItem) { // Add &
    println!("id: {:?}", item.id);
}

fn main() {
    let my_item = GroceryItem {
        quantity: 3,
        id: 99,
    };

    display_quantity(&my_item); // Add &
    display_id(&my_item); // Add &
}
/* 
Output
id:99
*/

impl

✨ 更多可看 Rust檔案

  • 關鍵字impl 重點是用來定義在型別的實作 (define implementations on types)
  • 原始型別之一(one of the primitive types)

Example 02 - 定義盒子的顏色

1.

  • 先建立枚舉定義顏色
  • 接著建立impl
enum Color {
    Brown,
    Red,
}

impl Color {
    fn print(&self) {
        match self {
            Color::Brown => println!("brown"),
            Color::Red => println!("red"),
        }
    }
}

2.

Implement functionality on the box struct to create a new box.

  • 在結構體(struct) box 建立一個新box,以便實作功能
struct Dimensions {
    width: f64,
    height: f64,
    depth: f64,
}

impl Dimensions {
    fn print(&self) {
        println!("width: {:?}", self.width);
        println!("height: {:?}", self.height);
        println!("depth: {:?}", self.depth);
    }
}


3.

在結構體box實作功能,並輸出其特性(characteristics)

struct ShippingBox {
    color: Color,
    weight: f64,
    dimensions: Dimensions,
}

impl ShippingBox {
    fn new(weight: f64, color: Color, dimensions: Dimensions) -> Self {
        Self {
            weight,
            color,
            dimensions,
        }
    }

    fn print(&self) {
        self.color.print();
        self.dimensions.print();
        println!("weight: {:?}", self.weight);
    }
}

4.

Print out.

fn main() {
    let small_dimensions = Dimensions {
        width: 1.0,
        height: 2.0,
        depth: 3.0,
    };  
    let small_box = ShippingBox::new(5.0, Color::Red, small_dimensions);
    small_box.print();
}

/* 
Red
width: 1.0
height: 2.0
depth: 3.0
weight: 5.0
*/

5.

完整程式碼

enum Color {
    Brown,
    Red,
}

impl Color {
    fn print(&self) {
        match self {
            Color::Brown => println!("brown"),
            Color::Red => println!("red"),
        }
    }
}

struct Dimensions {
    width: f64,
    height: f64,
    depth: f64,
}

impl Dimensions {
    fn print(&self) {
        println!("width: {:?}", self.width);
        println!("height: {:?}", self.height);
        println!("depth: {:?}", self.depth);
    }
}

struct ShippingBox {
    color: Color,
    weight: f64,
    dimensions: Dimensions,
}

impl ShippingBox {
    fn new(weight: f64, color: Color, dimensions: Dimensions) -> Self {
        Self {
            weight,
            color,
            dimensions,
        }
    }

    fn print(&self) {
        self.color.print();
        self.dimensions.print();
        println!("weight: {:?}", self.weight);
    }
}
fn main() {
    let small_dimensions = Dimensions {
        width: 1.0,
        height: 2.0,
        depth: 3.0,
    };  
    let small_box = ShippingBox::new(5.0, Color::Red, small_dimensions);
    small_box.print();
}

參考資料 Reference

Nice 教學影片


上一篇
Day 08 - 枚舉(Enum) & 元組(Tuples)
下一篇
Day 10 - 向量(Vector)
系列文
Let's go Rusty. 從0開始了解Rust.15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言