Rust中的方法(Methods)
整理自Rust 0.6 tutorial。Methods和函数类似,只不过第一个参数总是self,用来表明方法的接收者。self参数类似C++中的this指针,以及其它语言中的self。方法调用使用点符号,比如:my_vec.len()。
Implementations,以关键字impl开头,用来为大多数Rust类型定义方法,包括structs和enums。例如,我们为enum Shape定义一个draw方法。
struct Point { x: float, y: float } enum Shape { Circle(Point, float), Rectangle(Point, Point) } impl Shape { fn draw(&self) { match *self { Circle(p, f) => draw_circle(p, f), Rectangle(p1, p2) => draw_rectangle(p1, p2) } } } let s = Circle(Point { x: 1f, y: 2f }, 3f); s.draw();这样就为Shape定义了一个implementation,包含一个方法draw。draw方法定义和函数定义很类似,除了self参数。
self的类型是该方法接收者的类型,或者指针。self可以写成self, &self, @self,或者~self。调用者必须使用相容的指针类型来调用方法:
impl Shape { fn draw_borrowed(&self) { ... } fn draw_managed(@self) { ... } fn draw_owned(~self) { ... } fn draw_value(self) { ... } } let s = Circle(Point { x: 1f, y: 2f }, 3f); (@s).draw_managed(); (~s).draw_owned(); (&s).draw_borrowed(); s.draw_value();self通常使用borrowed pointer类型,所以编译器会尽可能地把方法接收者转换为borrowed pointer。
// As with typical function arguments, managed and unique pointers // are automatically converted to borrowed pointers (@s).draw_borrowed(); (~s).draw_borrowed(); // Unlike typical function arguments, the self value will // automatically be referenced ... s.draw_borrowed(); // ... and dereferenced (& &s).draw_borrowed(); // ... and dereferenced, and borrowed, and (&@~s).draw_borrowed();Implementations也可以定义static方法,静态方法不需要self参数。关键字static将静态方法和需要self的方法区分开来。
impl Circle { fn area(&self) -> float { ... } static fn new(area: float) -> Circle { ... } }
注:后续将移除static关键字,以是否存在self参数来区分静态方法和非静态方法。构造函数是静态方法最常使用的地方,比如上面的new。调用静态方法需要提供类型名前缀:
struct Circle { radius: float } impl Circle { static fn new(area: float) -> Circle { Circle { radius: sqrt(area / pi) } } } let c = Circle::new(42.5);
没有评论:
发表评论