- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 243字
- 2021-07-02 19:13:00
Associated types
We can also have types in a trait that need to be specified. For instance, let's implement the Add trait from the standard library on our Point type that we declared earlier, which allows us to use the + operator on our own types:
use std::ops::Add; impl Add<Point> for Point { type Output = Point; fn add(self, point: Point) -> Self::Output { Point { x: self.x + point.x, y: self.y + point.y, } } }
The first line is to import the Add trait from the standard library so that we can implement it on our type. Here we specify that the associated Output type is Point. Associated types are most useful for return types. Here, the Output of the add() method is the associated Self::Output type.
Now, we can use the + operator on Points:
let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 3, y: 4 }; let p3 = p1 + p2;
Having to specify the output parameter with an associated type (instead of setting it to Self) gives us more flexibility. For instance, we could implement the scalar product for the * operator, which takes two Points and returns a number.
You can find all the operators that can be overloaded on this page, at https://doc.rust-lang.org/stable/std/ops/index.html.
Since Rust 1.20, Rust also supports associated constants in addition to associated types.
- 地方檔案與文獻(xiàn)研究(第2輯)
- 智慧場館與智慧學(xué)習(xí)
- 肖鷹文集初編·批評卷
- 文件、信息商業(yè)化服務(wù)機(jī)構(gòu)建設(shè)研究
- 高校圖書館門戶網(wǎng)站建設(shè)(谷臻小簡·AI導(dǎo)讀版)
- 圖書館知識整合與知識服務(wù)研究:以西部社會科學(xué)院圖書館為例
- 李一氓文存(第四卷):古籍整理
- 高校圖書館閱讀推廣與宣傳促進(jìn)研究
- 信息系統(tǒng)工程(第2版)
- 中國人民大學(xué)“復(fù)印報(bào)刊資料”轉(zhuǎn)載指數(shù)排名研究報(bào)告(2014)
- 北京大學(xué)中國古文獻(xiàn)研究中心集刊·第十四輯
- 知中16·西南聯(lián)大的遺產(chǎn)
- 基于知識治理的競爭情報(bào)協(xié)同模型研究
- 檔案修復(fù)與歷史資料的數(shù)字化:第六屆東亞史料研究編纂機(jī)構(gòu)聯(lián)席會議論文集
- 圖書館服務(wù)均等化與資源共享(上冊)