Rust語言學習筆記(5)
阿新 • • 發佈:2018-08-12
完全 ack 結構 some not eight bject pixel ring
Structs(結構體)
struct User { username: String, email: String, sign_in_count: u64, active: bool, } let mut user1 = User { email: String::from("[email protected]"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; user1.email = String::from("[email protected]"); // 結構體初始化縮寫形式 fn build_user(email: String, username: String) -> User { User { email, // email: email, username, // username: username, active: true, sign_in_count: 1, } } // 結構體更新語法 let user2 = User { email: String::from("[email protected]"), username: String::from("anotherusername567"), ..user1 // active: user1.active, ... };
Tuple Structs(元組結構體)
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
- 元組結構體實質上是整體有名字但是成員沒有名字的元組。
- 成員完全相同但是結構體名字不同的兩個元組結構體不是同一個類型。
比如 Color 和 Point 是兩個類型。 - 可以定義完全沒有成員的單元元組結構體。
Debug 特質
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50 }; println!("rect1 is {:?}", &rect1); println!("rect1 is {:#?}", &rect1); } /* rect1 is Rectangle { width: 30, height: 50 } rect1 is Rectangle { width: 30, height: 50 } */
方法
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } impl Rectangle { fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } } } fn main() { let rect1 = Rectangle { width: 30, height: 50 }; println!( "The area of the rectangle is {} square pixels.", rect1.area() ); let rect2 = Rectangle { width: 10, height: 40 }; let rect3 = Rectangle { width: 60, height: 45 }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); let sq = Rectangle::square(3); } /* The area of the rectangle is 1500 square pixels. Can rect1 hold rect2? true Can rect1 hold rect3? false */
- 定義方法采用 impl 關鍵字。方法在結構體之外的 impl 塊中定義。
- 方法簽名中指向結構體自身的參數有3種形式:self, &self, &mut self。
- self 參數不需要標註類型。
- 調用方法采用 object.method() 語法。
object 形式固定,無論方法簽名中的 self 參數采用何種形式。 - 同一個結構體的方法可以定義在多個 impl 塊中。
- impl 塊中可以定義不帶 self 參數的函數。這些函數通常用作構造器。
Rust語言學習筆記(5)