- 一旦struct的实例是可变的,那么实例中所有的字段都是可变的,不允许单独声明一部分可变。
- struct 更新语法:当你想基于某个struct实例来创建一个新实例时,可以用struct更新语法:
let user2 = User {
emails: String::from("another@example.com"),
usernames: String::from("anotherusernames567"),
..user1
};
- Tuple struct:适用于:想给整个tuple起名,并让它不同于其他tuple,而且又不需要给每个元素起名。
struct Color(i32, i32);
let black = Color(0, 0);
println!("{}, {}", black.0, black.1);
- 可以定义没有任何字段的struct, Unit-like struct。
- struct数据的所有权,可以存放引用,但这需要生命周期。
- 可以在impl定义方法。
struct User {
usernames: String,
emails: String,
sign_in_counts: u64,
activates: bool,
}
#[derive(Debug)] //原来这个东西要放在对应struct定义前一行呀
struct Rectangle {
width: u32,
length: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
// 代码清晰,易于维护
self.length * self.width
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.length > other.length
}
// 关联函数
fn square(size: u32) -> Rectangle {
Rectangle { width: size, length: size }
}
}
fn main() {
println!("Hello, world!");
// 使用点标记法获取struct里的值
let user1 = User {
emails: String::from("acb@126.com"),
usernames: String::from("Nikky"),
activates: true,
sign_in_counts: 556,
};
println!("{}, {}, {}, {}", user1.emails, user1.activates, user1.sign_in_counts, user1.usernames);
// let user2 = User {
// emails: String::from("another@example.com"),
// usernames: String::from("anotherusernames567"),
// ..user1
// };
struct Color(i32, i32);
let black = Color(0, 0);
println!("{}, {}", black.0, black.1);
// 计算面积
let rect= Rectangle {
width: 30,
length: 50,
};
println!("面积为{}", rect.area());
println!("{:#?}", rect);
// 继续练习
let rect1= Rectangle {
width: 30,
length: 50,
};
let rect2= Rectangle {
width: 10,
length: 40,
};
let rect3= Rectangle {
width: 35,
length: 25,
};
println!("{}", rect1.can_hold(&rect2));
println!("{}", rect2.can_hold(&rect3));
let s = Rectangle::square(80);
println!("{:#?}", s)
}
// fn build_user(emails: String, usernames: String) -> User {
// // 初始化简写
// User {
// emails,
// usernames,
// activates: true,
// sign_in_counts: 0,
// }
// }
// fn area(rect: &Rectangle) -> u32 {
// // 代码清晰,易于维护
// rect.length * rect.width
// }