- 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.
- 大數(shù)據(jù)環(huán)境下圖書(shū)館文獻(xiàn)信息資源建設(shè)與利用
- 面向青少年的博物館教育(上下卷)
- 蒲城文獻(xiàn)征錄
- 博物館新視覺(jué):博物館管理叢書(shū)
- 人文通識(shí)講演錄:人文教育卷
- 科學(xué)名家
- 美華書(shū)館:檔案如是說(shuō)(新聞出版博物館文庫(kù)·研究)
- 國(guó)外圖書(shū)情報(bào)知識(shí)圖譜實(shí)證研究
- 圖書(shū)情報(bào)專業(yè)碩士培養(yǎng)研究與實(shí)踐
- 法學(xué)研究與文獻(xiàn)檢索
- 西夏檔案及其管理制度研究
- 中國(guó)人民大學(xué)復(fù)印報(bào)刊資料轉(zhuǎn)載指數(shù)排名研究報(bào)告2018(中國(guó)人民大學(xué)研究報(bào)告系列)
- 計(jì)算社會(huì)學(xué)
- 檔案與少數(shù)民族記憶
- 新國(guó)學(xué)(第十五卷)