- Rust Programming By Example
- Guillaume Gomez Antoni Boucher
- 251字
- 2021-07-02 19:12:59
Traits
Traits are a way to specify that a type must implement some methods and/or some types. They are similar to interfaces in Java. We can implement a trait on a type and we'll be able to use the methods of this trait on this type as long as this trait is imported. This is how we can add methods to types defined in other crates or even the standard library.
Let's write a trait representing a bit set:
trait BitSet { fn clear(&mut self, index: usize); fn is_set(&self, index: usize) -> bool; fn set(&mut self, index: usize); }
Here, we don't write the body of the methods, as they will be defined when we implement this trait for a type.
Now, let's implement this trait for the u64 type:
impl BitSet for u64 { fn clear(&mut self, index: usize) { *self &= !(1 << index); } fn is_set(&self, index: usize) -> bool { (*self >> index) & 1 == 1 } fn set(&mut self, index: usize) { *self |= 1 << index; } }
As you can see, the bitwise not operator is ! in Rust, as opposed to ~ in other languages. With this code, we can call these methods on u64:
let mut num = 0; num.set(15); println!("{}", num.is_set(15)); num.clear(15);
Remember the #[derive(Debug)] attribute? This actually implements the Debug trait on the following type. We could also manually implement the Debug trait on our type, using the same impl syntax, if the default implement does not suit our use case.
- 問學:思勉青年學術集刊(第2輯)
- 中國人民大學復印報刊資料轉載指數排名研究報告2016
- 公共文化館治理研究(2015年):四川省文化館“十三五”規劃重大課題調研成果集
- 國內圖書情報知識圖譜實證研究
- 中國城市遺址類博物館開發模式研究
- Learning Robotics using Python
- 圖書館知識整合與知識服務研究:以西部社會科學院圖書館為例
- 清代地方檔案的保存、整理與研究
- 知中8·了不起的宋版書
- 科學名家
- 檔案檢索: 理論與方法
- 地方政府數字檔案集中管理模式研究(國家社會科學基金項目成果)
- 探索與實踐:博物館與口述歷史
- Practical Industrial Internet of Things Security
- 美華書館:檔案如是說(新聞出版博物館文庫·研究)