方法
方法是与某种类型关联的函数。方法的 self
参数是与其关联类型的一个实例:
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn inc_width(&mut self, delta: u32) { self.width += delta; } } fn main() { let mut rect = Rectangle { width: 10, height: 5 }; println!("old area: {}", rect.area()); rect.inc_width(5); println!("new area: {}", rect.area()); }
- 我们将在今天的练习和明天的课程中更深入地学习方法相关的概念。
-
Add a static method called
Rectangle::new
and call this frommain
:fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height } }
-
虽然从技术层面来讲,Rust 没有自定义构造函数,但静态方法通常用于初始化结构体(但并非必须这样做)。您可以直接调用实际构造函数“Rectangle { width, height }”。请参阅 Rust 秘典。
-
Add a
Rectangle::square(width: u32)
constructor to illustrate that such static methods can take arbitrary parameters.