使用struct定义结构体,在花括号中声明数据名字和类型:
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
结构体的实例化(赋值):
let 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,
username: username,
active: true,
sign_in_count: 1,
}
}
字段名与变量名相同,可以简化初始化方法:
fn build_user(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
下代码,除了email和username,其余值都与user1的值一样:
let user2 = User {
email: String::from("[email protected]"),
username: String::from("anotherusername567"),
active: user1.active,
sign_in_count: user1.sign_in_count,
};
通过更新语法,我们可以使用更少的代码实现相同的效果:
let user2 = User {
email: String::from("[email protected]"),
username: String::from("anotherusername567"),
..user1
};
fn main() {
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
}
这种方法只规定了类型,且实例行为与元组一样。需要注意的时black和origin是不同类型的。
rust允许空结构体,可以用来实现trait,之后讨论。
涉及生命周期,之后讨论。