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

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;
    }
}
主站蜘蛛池模板: 嘉鱼县| 普陀区| 云梦县| 兴化市| 旺苍县| 兴义市| 仁化县| 黄陵县| 黄龙县| 南丹县| 社旗县| 崇义县| 沁水县| 临泽县| 丰顺县| 且末县| 延吉市| 拉孜县| 高青县| 皋兰县| 北辰区| 资阳市| 铁力市| 沅陵县| 莎车县| 汤原县| 中方县| 钟山县| 东乌| 玉林市| 阜平县| 莱芜市| 红原县| 勐海县| 怀柔区| 清流县| 武夷山市| 淮滨县| 义乌市| 五大连池市| 习水县|