- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 222字
- 2021-07-02 19:13:00
Generics
Generics are a way to make a function or a type work for multiple types to avoid code duplication. Let's rewrite our max function to make it generic:
fn max<T: PartialOrd>(a: T, b: T) -> T { if a > b { a } else { b } }
The first thing to note is that there's a new part after the function name: this is where we declare the generic types. We declare a generic T type, : PartialOrd after it means that this T type must implement the PartialOrd trait. This is called a trait bound. We then use this T type for both of our parameters and the return type. Then, we see the same function body as the one from our non-generic function. We needed to add the trait bound because, by default, no operation is allowed on a generic type. The PartialOrd trait allows us to use the comparison operators.
We can then use this function with any type that implements PartialOrd:
println!("{}", max('a', 'z'));
This is using static dispatch as opposed to dynamic dispatch, meaning that the compiler will generate a max function specific to char in the resulting binary. Dynamic dispatch is another approach that resolves the right function to call at runtime, which is less efficient.
- 普通高校中文學(xué)科基礎(chǔ)教材古典文獻(xiàn)學(xué)基礎(chǔ)
- 社會網(wǎng)絡(luò)分析方法在圖書情報領(lǐng)域的應(yīng)用研究
- 國內(nèi)圖書情報知識圖譜實證研究
- 網(wǎng)絡(luò)學(xué)術(shù)信息老化及應(yīng)對管理
- 混搭文綴
- 檔案庫房技術(shù)管理
- 邂逅法學(xué)圖書館:浙江大學(xué)光華法學(xué)院師生原創(chuàng)文集
- Rust Programming By Example
- 圖書情報與圖書館服務(wù)探究
- 且為繁華寄書香:高校圖書館閱讀推廣理論與實務(wù)
- Practical Mobile Forensics(Third Edition)
- 科技服務(wù)研究
- 一本書的圖書館之旅:圖書館閱讀推廣十五年
- 心智與閱讀
- 北京大學(xué)中國古文獻(xiàn)研究中心集刊 第十三輯