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

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;
    }
}
主站蜘蛛池模板: 沐川县| 区。| 修文县| 通辽市| 怀安县| 伊宁市| 昌江| 马关县| 宾阳县| 汶上县| 乌兰浩特市| 婺源县| 台州市| 阿克苏市| 古浪县| 来安县| 青铜峡市| 宜州市| 历史| 英山县| 凤翔县| 吕梁市| 九江县| 兴业县| 静海县| 泗水县| 绥宁县| 台山市| 乌恰县| 两当县| 铁岭市| 南投市| 福海县| 金湖县| 乌海市| 丹棱县| 安龙县| 陕西省| 万山特区| 胶州市| 图们市|