Rust學習(14):結構體與方法與關聯函數

獲取以像素爲單位的長方形的寬度和高度,並計算出長方形的面積

文章目錄

使用結構體

struct Rectangle{
    width:u32,
    height:u32,
}

fn main() {
    let rect = Rectangle{
        width:10,
        height:10,
    };

    let area:u32 = rectangele_area(&rect);//傳引用,否則這個正方形就會失去它的屬性的所有權,屬性是不能借的,是自己固有的
    println!("{}", area);
}

fn rectangele_area(rect:&Rectangle)->u32{
    return rect.width * rect.height;
}
  • 方法與函數類似,它們使用fn關鍵字和名稱聲明,可以擁有參數和返回值,同時包含在某處調用該方法時會執行的代碼。不過方法與函數是不同的,因爲它們在結構體的上下文中被定義,並且它們的第一個參數總是self,它代表調用該方法的結構體實例
  • 調用方法:使用.運算符調用實例的方法

方法允許爲結構體實例指定行爲

//
struct Rectangle{
    width:u32,
    height:u32,
}

impl Rectangle{
     //這個結構體擁有求面積的方法
    fn area(&self)->u32{   //不可變地借用 self:我們並不想獲取所有權,只希望能夠讀取結構體中的數據,而不是修改寫入結構體數據。
         return self.width * self.height;
    }

    //行爲:長方形能否包含另一個長方形
    fn can_hold(&self, other:&Rectangle)->bool{
        return self.height > other.height && self.width > other.width;
    }

    fn change_width(&mut self, width:u32){
        self.width = width;
    }
}

fn main() {
    let rect1 = Rectangle{
        width:10,
        height:10,
    };

    let mut rect2 = Rectangle{
        width:5,
        height:5,
    };

    println!("the rectangle's area is {}", rect1.area());
    println!("rect1 can hold rect2 ? {}", rect1.can_hold(&rect2)); //可變變量允許以不允許修改的權限借出自己的值

    rect2.change_width(15);
    println!("{}", rect2.width)
}
  • impl的另一個有用的功能是:允許在impl中定義不以self作爲參數的函數,這被稱爲關聯函數,因爲它們與結構體相關聯。但是它們仍然是函數而不是方法,
    因爲它們並不作用於一個結構體的實例。
  • 使用方法:使用::運算符。::語法用於關聯函數和模塊創建的命名空間
//
struct Rectangle{
    width:u32,
    height:u32,
}

impl Rectangle{
     //這個結構體擁有求面積的方法
    fn area(&self)->u32{   //不可變地借用 self:我們並不想獲取所有權,只希望能夠讀取結構體中的數據,而不是修改寫入結構體數據。
         return self.width * self.height;
    }

    //行爲:長方形能否包含另一個長方形
    fn can_hold(&self, other:&Rectangle)->bool{
        return self.height > other.height && self.width > other.width;
    }

    fn change_width(&mut self, width:u32){
        self.width = width;
    }
}

//關聯函數
impl Rectangle{
    //關聯函數常常被用作返回一個結構體新實例的函數,比如構建一個正方形的關聯函數:
    fn square(size:u32)->Rectangle{
        return Rectangle{width:size, height:size}
    }
}
fn main() {
    let square1 = Rectangle::square(15);
    let area = square1.area();
    println!("area is {}", area);
}

參考:https://kaisery.github.io/trpl-zh-cn/ch05-03-method-syntax.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章