Skip to content
On this page

Rust方法语法


标签:rust/basic  

✍读书笔记:『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()             
    );
}
  1. 定义 impl 块,和结构体 Rectangle 同名
  2. 其中的函数签名中,可以使用&self替代rectangel:&Rectangle
  3. self可以是借用&,也可以移动
  4. 调用的时候可以使用结构体.方法名
  5. 方法名可以和结构体字段名重名,通常作为gettersetter
  6. impl块可以是分散的多个,都是有效的
  7. Self类型可以作为结构体类型:
rust
impl Rectangle {
    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }
}

Last updated: