官术网_书友最值得收藏!

Methods

We can add methods on custom types. Let's write a method to compute the distance of a point to the origin:

impl Point {
    fn dist_from_origin(&self) -> f64 {
        let sum_of_squares = self.x.pow(2) + self.y.pow(2);
        (sum_of_squares as f64).sqrt()
    }
}

There are a lot of new syntaxes here (impl Point, as, and .method()), so let's explain all of them. First of all, methods of a type are declared within the impl Type {} construct. This method takes a special parameter: &self. This parameter is the instance the method is called on, like this in other programming languages. The & operator before self means that the instance is passed by immutable reference. As we can see, it is possible to call methods on basic types in Rust—self.x.pow(2) computes the power of two of the x field. We can find this method, and many others, in the documentation, at https://doc.rust-lang.org/stable/std/primitive.i32.html#method.pow . In the last expression of the method, we cast the sum_of_squares integer to f64 before computing its square root, because the sqrt() method is defined only on floating points.

Let's create a method that will update the fields of the structure:

impl Point {
    fn translate(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }
}

The difference with the previous method is that self is now a mutable reference, &mut.

主站蜘蛛池模板: 新兴县| 澄城县| 屏南县| 齐齐哈尔市| 温泉县| 阿荣旗| 文登市| 娄底市| 福泉市| 滦平县| 喀什市| 余庆县| 邢台县| 邓州市| 嘉善县| 双辽市| 鄂托克旗| 平乡县| 合作市| 云阳县| 莱西市| 呼玛县| 孟连| 孟连| 珠海市| 龙南县| 楚雄市| 武胜县| 南漳县| 汾阳市| 萨迦县| 江陵县| 佛教| 江油市| 怀远县| 谢通门县| 龙门县| 高尔夫| 长沙市| 静宁县| 漾濞|