- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 236字
- 2021-07-02 19:12:58
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.
- 問學(xué):思勉青年學(xué)術(shù)集刊(第2輯)
- 區(qū)塊鏈在電子檔案管理中的應(yīng)用
- 智慧場(chǎng)館與智慧學(xué)習(xí)
- 單讀. 十周年特輯(時(shí)間的移民+在世界的門外)共2冊(cè)
- 公共圖書館文獻(xiàn)信息資源政府采購(gòu)
- 中國(guó)古典文獻(xiàn)學(xué)(東北師范大學(xué)文學(xué)院學(xué)術(shù)史文庫(kù))
- 邂逅法學(xué)圖書館:浙江大學(xué)光華法學(xué)院師生原創(chuàng)文集
- 法學(xué)研究與文獻(xiàn)檢索
- 文獻(xiàn)價(jià)值:理論文獻(xiàn)學(xué)的價(jià)值論解讀
- 圖書館服務(wù)管理內(nèi)化:概念、過程及整合因素
- 當(dāng)代博物館的新角色與新視野
- 圖書館出版物國(guó)際交換
- 兒童閱讀的世界Ⅳ:學(xué)校、家庭與社區(qū)的實(shí)踐研究
- 抗戰(zhàn)時(shí)期中國(guó)圖書館界研究
- 心智與閱讀