struct User {active: bool,username: String,email: String,sign_in_count: u64,}fn main() {let mut user1 = User {email: String::from("someone@example.com"),username: String::from("someusername123"),active: true,sign_in_count: 1,};user1.email = String::from("anotheremail@example.com");}
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, // 因为 email 字段与 email 参数有着相同的名称username,active: true,sign_in_count: 1,}}
// 使用结构体更新语法从其他实例创建实例fn main() {// --snip--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};}
结构更新语法就像带有 = 的赋值,因为它移动了数据,就像我们在“变量与数据交互的方式(一):移动”部分讲到的一样。在这个例子中,我们在创建 user2 后不能再使用 user1,因为 user1 的 username 字段中的 String 被移到 user2 中。如果我们给 user2 的 email 和 username 都赋予新的 String 值,从而只使用 user1 的 active 和 sign_in_count 值,那么 user1 在创建 user2 后仍然有效。active 和 sign_in_count 的类型是实现 Copy trait 的类型,所以我们在“变量与数据交互的方式(二):克隆” 部分讨论的行为同样适用。
元组结构体(tuple structs)
struct Color(i32, i32, i32);struct Point(i32, i32, i32);fn main() {let black = Color(0, 0, 0);let origin = Point(0, 0, 0);}
类单元结构体(unit-like structs)
struct AlwaysEqual;fn main() {let subject = AlwaysEqual;}
