- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 125字
- 2021-07-02 19:12:59
Default methods
Traits can contain default methods, which can be convenient for the implementor of the trait since fewer methods will need to be implemented. Let's add a toggle() default method in the trait:
trait BitSet { fn clear(&mut self, index: usize); fn is_set(&self, index: usize) -> bool; fn set(&mut self, index: usize); fn toggle(&mut self, index: usize) { if self.is_set(index) { self.clear(index); } else { self.set(index); } } }
Since the new method has a body, we don't need to update our previous implementation. However, we could do it to provide a more efficient implementation, for instance:
impl BitSet for u64 { // The other methods are the same as before. fn toggle(&mut self, index: usize) { *self ^= 1 << index; } }
推薦閱讀
- 區(qū)塊鏈在電子檔案管理中的應(yīng)用
- 胡華文集(第一卷)
- 中國人民大學(xué)復(fù)印報(bào)刊資料轉(zhuǎn)載指數(shù)排名研究報(bào)告2016
- 國外圖書館動漫資源建設(shè)與服務(wù)
- 公益 創(chuàng)新 服務(wù)
- 新時(shí)代檔案工作新思維
- 清代地方檔案的保存、整理與研究
- 探索與實(shí)踐:博物館與口述歷史
- 檔案智慧化管理與開發(fā)利用的探索研究
- 西夏檔案及其管理制度研究
- 圖書館學(xué)基礎(chǔ)簡明教程
- 信息檢索與案例研究
- 李一氓文存(第一卷):存在集·存在集續(xù)編
- “秦陵杯”講解員職業(yè)技能大賽講解詞匯編
- 梁思成林徽因影像與手稿珍集