struct User { username: String, email: String, sign_in_count: u64, active: bool, }
这样能够定义一个结构体。python
当已有一个结构体User1时:函数
let user2 = User { email: String::from("another@example.com"), username: String::from("anotherusername567"), ..user1 };
能够这样把剩余的字段赋值为和user1相同的值。blog
struct Point(i32, i32, i32); let origin = Point(0, 0, 0);
这样便定义了一个元组结构体,在你但愿命名一个元组时颇有用。class
结构体内能够实现方法:email
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }
这样调用:方法
let rect1 = Rectangle { width: 30, height: 50 }; rect1.area();
一个impl内能够实现若干方法,一个结构体也能够有多个impl。im
impl Rectangle { fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } } }
这样调用关联函数:命名
let sq = Rectangle::square(3);