3.2 结构体
- rust中没有class
struct
- 包含多段数据的类型
- 每一段数据被称为
field
属性 - 访问属性用
.
#[derive(Debug)]
struct Rectangle {
width: i32,
height: i32,
}
fn main() {
let rect = Rectangle {
width: 5,
height: 10,
};
println!("{}", rect.width);
println!("{:#?}", rect);
}
struct 方法
- 关联函数
- 实例方法
- 构造函数
- Self
示例1
#[derive(Debug)]
struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
// 关联函数
fn area(width: i32, height: i32) -> i32 {
width * height
}
// 实例方法
fn cal(&self) -> i32 {
self.width * self.height
}
// 构造函数
fn new(width: i32, height: i32) -> Self {
Rectangle {
width, height }
}
}
fn main() {
let rect = Rectangle {
width: 5,
height: 10,
};
let num1 = Rectangle::area(5, 5);
println!("{}", num1);
println!("{}", rect.cal());
let rect2 = Rectangle::new(5, 5);
println!("{:#?}", rect2);
}
示例2
#[derive(Debug)]
struct Person {
name: String,
age: i32,
}
impl Person {
// 可能在外部调用,使用pub关键字
pub fn new(name: String, age: i32) -> Self {
Person {
name, age }
}
}
fn main() {
let person1 = Person::new("Star-tears".to_string(), 18);
println!("{:#?}", person1);
}
- &self
- &mut self
- self
- mut self
示例3
#[derive(Debug)]
struct Person {
name: String,
age: i32,
}
impl Person {
// 可能在外部调用,使用pub关键字
pub fn new(name: String, age: i32) -> Self {
Person {
name, age }
}
fn greet(&self) -> String {
format!("Hi {}", self.name)
}
fn add_age(&mut self, n: i32) {
self.age += n;
}
}
fn main() {
let mut person1 = Person::new("Star-tears".to_string(), 18);
println!("{:#?}", person1);
println!("{}", person1.greet());
person1.add_age(3);
println!("{}", person1.age);
}
&
为引用,但默认是不可变的,如果希望可变,需要加mut
关键字