Rust(6) - Structure

1. 宣告 Structure:

Structure 可以有意義地集合資料,跟 tuple 或 array 比起來有較高的可讀性。

fn main() {
    let rect = Rectangle {
        x: 0.0, 
        y: 0.0, 
        w: 1.0,
        h: 3.0,
    };
    println!("x: {}, y: {}, w: {}, h: {}", 
        rect.x, rect.y, rect.w, rect.h);
}

struct Rectangle {
    x: f32,
    y: f32,
    w: f32,
    h: f32,
}

用 tuple 也可以達成類似的功能並收集不同型別的資料,但不具可讀性。

let rect: (f32, f32, f32, f32) = (0.0, 0.0, 1.0, 3.0);

2. 幫 Structure 添加 function:

透過 impl 我們可以幫 Structure 添加專屬方法,&self 是一個自引用代表物件本身。

fn main() {
    let rect = Rectangle {
        x: 0.0, 
        y: 0.0, 
        w: 1.0,
        h: 3.0,
    };
    println!("Area: {}", rect.area());
    rect.center();
}

#[derive(Debug)]
struct Rectangle {
    x: f32,
    y: f32,
    w: f32,
    h: f32,
}

impl Rectangle {
    fn area(&self) -> f32 {
        self.w * self.h
    }

    fn center(&self) {
        println!("Center is {}, {}", self.x, self.y);
    }
}

impl 中的方法可以分開,舉個例子。

impl Rectangle {
    fn area(&self) -> f32 {
        self.w * self.h
    }
}

impl Rectangle {
    fn center(&self) {
        println!("Center is {}, {}", self.x, self.y);
    }
}

Structure in Go:

附上 Go 的 struct,感覺 Go 跟 Rust 是兩兄弟寫法幾乎一樣XD

package main

import "fmt"

func main() {
    rect := Rectangle{
        0,
        0,
        1,
        3,
    }
    fmt.Printf("Area: %.3f\n", rect.Area())
    fmt.Printf("Center is %.3f, %.3f\n", rect.x, rect.y)
}

type Rectangle struct {
    x float32
    y float32
    w float32
    h float32
}

func (rect *Rectangle) Area() float32 {
    return rect.w * rect.h
}

func (rect *Rectangle) Center() (float32, float32) {
    return rect.x, rect.y
}

留言

熱門文章