rust中的self与Self

发布时间 2023-04-28 17:14:26作者: wenli7363

self

self 是一个代表类型实例(或者是类型的引用或者是值)的关键字,在 Rust 的方法中使用 self 可以引用当前类型的实例或者类型本身

具体来说,当我们定义一个方法时,使用 self 关键字作为方法的第一个参数可以让我们在调用该方法时直接访问类型实例本身

struct Point {
    x: f32,
    y: f32,
}

impl Point {
    fn distance(&self, other: &Point) -> f32 {
        let dx = self.x - other.x;
        let dy = self.y - other.y;
        (dx * dx + dy * dy).sqrt()
    }
}

Self

通常在 Rust 的 trait 和 associated function 中使用 Self 来指代实现该 trait 或调用该 associated function 的类型。

struct Point {
    x: f32,
    y: f32,
}

impl Point {
    //关联函数
    fn origin() -> Self {
        Point { x: 0.0, y: 0.0 }
    }
}

fn main() {
    let p = Point::origin();
}