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

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;
    }
}
主站蜘蛛池模板: 山阴县| 武陟县| 台中县| 石河子市| 涞源县| 潞城市| 苍梧县| 灵山县| 淮北市| 昭觉县| 民勤县| 黑山县| 繁昌县| 大同县| 同心县| 泾川县| 伊宁县| 益阳市| 望奎县| 澄城县| 大庆市| 灵台县| 金山区| 兴山县| 霍林郭勒市| 墨竹工卡县| 龙海市| 高雄县| 抚顺市| 梁山县| 桑植县| 铜山县| 阿拉善盟| 太仆寺旗| 胶州市| 徐闻县| 自贡市| 色达县| 遂川县| 利辛县| 海城市|