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

  • 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;
    }
}
主站蜘蛛池模板: 永昌县| 城固县| 江安县| 荆门市| 策勒县| 延庆县| 延安市| 馆陶县| 蚌埠市| 常德市| 金寨县| 达拉特旗| 东乡县| 隆德县| 古浪县| 苍梧县| 京山县| 怀安县| 轮台县| 阳春市| 靖远县| 闻喜县| 九江市| 九江市| 额敏县| 宾阳县| 江城| 合阳县| 东乡| 绍兴县| 岳普湖县| 绩溪县| 安塞县| 鹿泉市| 丹阳市| 沂南县| 玉树县| 资阳市| 新平| 北辰区| 巴彦淖尔市|