官术网_书友最值得收藏!

  • 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;
    }
}
主站蜘蛛池模板: 台湾省| 新巴尔虎左旗| 宁乡县| 淅川县| 望谟县| 六枝特区| 贵南县| 彩票| 特克斯县| 扎兰屯市| 浪卡子县| 隆回县| 乳山市| 娄烦县| 林周县| 修水县| 扬中市| 苍梧县| 大安市| 衢州市| 岑溪市| 日土县| 东辽县| 青州市| 古蔺县| 白沙| 海门市| 武义县| 通榆县| 泰州市| 西宁市| 微博| 昔阳县| 崇文区| 饶平县| 霞浦县| 吉隆县| 濮阳市| 抚远县| 民县| 安塞县|