- 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.
- 國(guó)外圖書館動(dòng)漫資源建設(shè)與服務(wù)
- Learning Robotics using Python
- 人文通識(shí)講演錄:人文教育卷
- 山東圖書館學(xué)史研究
- 探索與實(shí)踐:博物館與口述歷史
- 文獻(xiàn)學(xué)與歷史研究
- 檔案記憶觀的理論與實(shí)踐
- 檔案與少數(shù)民族記憶
- 黨校圖書館轉(zhuǎn)型發(fā)展實(shí)踐研究
- Web 2.0環(huán)境中參與式的信息檔案化管理:走向全景檔案世界
- 數(shù)字信息環(huán)境下圖書館信息資源建設(shè)與共享
- 心智與閱讀
- 中國(guó)人民大學(xué)復(fù)印報(bào)刊資料轉(zhuǎn)載指數(shù)排名研究報(bào)告2015
- 信息檢索
- 圖書館學(xué)是什么