热门

最新

红包

立Flag

投票

同城

我的

发布
ilypl
软硬兼吃曹达华
3 年前
trueilypl

方法(method)是依附于对象的函数。这些方法通过关键字 self 来访问对象中的数据和其他。方法在 impl 代码块中定义。

CSDN App 扫码分享
分享
评论
1
打赏
  • 复制链接
  • 举报
下一条:
struct Point { x: f64, y: f64, } // 实现的代码块,`Point` 的所有方法都在这里给出 impl Point { // 这是一个静态方法(static method) // 静态方法不需要被实例调用 // 这类方法一般用作构造器(constructor) fn origin() -> Point { Point { x: 0.0, y: 0.0 } } // 另外一个静态方法,需要两个参数: fn new(x: f64, y: f64) -> Point { Point { x: x, y: y } } } struct Rectangle { p1: Point, p2: Point, } fn perimeter(&self) -> f64 { let Point { x: x1, y: y1 } = self.p1; let Point { x: x2, y: y2 } = self.p2; 2.0 * ((x1 - x2).abs() + (y1 - y2).abs()) } // 这个方法要求调用者是可变的 // `&mut self` 为 `self: &mut Self` 的语法糖 fn translate(&mut self, x: f64, y: f64) { self.p1.x += x; self.p2.x += x; self.p1.y += y;
立即登录