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

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;
    }
}
主站蜘蛛池模板: 政和县| 靖安县| 安远县| 共和县| 远安县| 九江市| 兴化市| 独山县| 子洲县| 日照市| 阿拉善右旗| 甘德县| 邹平县| 河北区| 新野县| 壶关县| 弋阳县| 久治县| 和平区| 珠海市| 库车县| 当涂县| 贵阳市| 都昌县| 临江市| 马关县| 铁力市| 垦利县| 镇平县| 望城县| 高州市| 丰都县| 新田县| 商洛市| 望都县| 东乌珠穆沁旗| 阿拉善盟| 普安县| 阳东县| 任丘市| 普格县|