结构体
土豆 2023/2/15
# 定义并实例化结构体
结构体定义
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
创建结构体
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
修改结构体示例中的字段
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
// 修改email值
user1.email = String::from("anotheremail@example.com");
接收邮箱和⽤户名作为参数并返回 User 实例的函数 build_user
fn build_user(email: String, username: String) -> User {
User {
username,
email,
active: true,
sign_in_count: 1,
}
}
根据其他实例创建新实例
let user2 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername567"),
active: user1.active,
sign_in_count: user1.sign_in_count,
};
let user2 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername567"),
..user1
};
元组的⽅式定义结构体
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
# ⼀个使⽤结构体的⽰例程序
fn main() {
let width1 = 30;
let height1 = 30;
println!(
"The area of the rectangle is {} square pixels.",
area(width1, height1)
)
}
fn area(width: u32, height: u32) -> u32 {
width * height
}
使⽤元组来重构代码
fn main() {
let react1 = (30, 50);
println!(
"The area of the rectangle is {} square pixels.",
area(react1)
)
}
fn area(dimensions: (u32, u32)) -> u32 {
dimensions.0 * dimensions.1
}
使用结构体来重构代码
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
area(&rect1)
)
}
fn area(rectangle: &Rectangle) -> u32 {
rectangle.width * rectangle.height
}
# 定义方法
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
)
}
更多参数的⽅法
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2?{}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3?{}", rect1.can_hold(&rect3));
}