定义结构体,需要使用 struct
关键字并为整个结构体提供一个名字。结构体的名字需要描述它所组合的数据的意义。接着,在大括号中,定义每一部分数据的名字和类型,我们称为 字段(field)。
1 定义
struct 类型名 { 变量名 : 变量类型, ... }; struct User { active: bool, username: String, email: String, sign_in_count: u64, }
2 创建结构体
let mut user1 = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; // 修改结构体字段 user1.email = String::from("anotheremail@example.com");
-
提供方法
fn build_user(email: String, username: String) -> User { User { active: true, username: username, email: email, sign_in_count: 1, } } // 简易方法 因为 username 和 email 参数与结构体字段同名 fn build_user(email: String, username: String) -> User { User { active: true, username, email, sign_in_count: 1, } }
-
通过结构体更新语法从其他实例创建实例
let user2 = User { active: user1.active, username: user1.username, email: String::from("another@example.com"), sign_in_count: user1.sign_in_count, }; // .. 语法指定了剩余未显式设置值的字段应有与给定实例对应字段相同的值。 let user2 = User { email: String::from("another@example.com"), ..user1 };
-
使用没有命名字段的元组结构体来创建不同的类型
也可以定义与元组(类似的结构体,称为 元组结构体(tuple structs)。元组结构体有着结构体名称提供的含义,但没有具体的字段名,只有字段的类型。当你想给整个元组取一个名字,并使元组成为与其他元组不同的类型时,元组结构体是很有用的,这时像常规结构体那样为每个字段命名就显得多余和形式化了。
要定义元组结构体,以
struct
关键字和结构体名开头并后跟元组中的类型。
struct Color(i32, i32, i32); let color = Color(0, 1, 2);
-
没有任何字段的类单元结构体
定义一个没有任何字段的结构体!它们被称为 类单元结构体(unit-like structs)因为它们类似于
()
,即元组类型一节中提到的 unit 类型。类单元结构体常常在你想要在某个类型上实现 trait 但不需要在类型中存储数据的时候发挥作用。struct AlwaysEqual; let subject = AlwaysEqual;
结构体的方法和实现的trait
use core::cmp::Ordering; # [derive(Debug, Eq, PartialEq, Ord)] pub struct Matrix { pub col : u32, pub row : u32, } impl Matrix { pub fn area(&self) -> u64 { (self.col * self.row) as u64 } pub fn print_matrix(&self) { println!("the matrix info col : {}, row : {}", self.col, self.row) } pub fn create_matrix(col : u32, row : u32) -> Matrix { Matrix { col, row, } } // other fucntions } impl PartialOrd for Matrix { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { // 先比较行在比较列 if self.col == other.col { return Some(self.row.cmp(&other.row)); } Some(self.col.cmp(&other.col)) } }