Appearance
✍读书笔记:『Rusts程序设计语言』ch05 - 03
Rust 方法
Rust 中没有 class,它使用『结构体 + 方法』的方式实现类似面向对象的模式。
方法和函数有区别,它的第一个参数总是 self。
定义方法
rust
#[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()
);
}- 定义
impl块,和结构体Rectangle同名 - 其中的函数签名中,可以使用
&self替代rectangel:&Rectangle self可以是借用&,也可以移动- 调用的时候可以使用
结构体.方法名 - 方法名可以和结构体字段名重名,通常作为
getter和setter impl块可以是分散的多个,都是有效的Self类型可以作为结构体类型:
rust
impl Rectangle {
fn square(size: u32) -> Self {
Self {
width: size,
height: size,
}
}
}