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

Macros

Macro rules, also called macros by example, are a way to avoid code duplication by generating code at compile time. We will implement a simple macro to implement our BitSet trait for integer types:

macro_rules! int_bitset {
    ($ty:ty) => {
        impl BitSet for $ty {
            fn clear(&mut self, index: usize) {
                *self &= !(1 << index);
            }

            fn is_set(&self, index: usize) -> bool {
                (*self >> index) & 1 == 1
            }

            fn set(&mut self, index: usize) {
                *self |= 1 << index;
            }
        }
    };
}

The name of the int_bitset macro is written after macro_rules!. A macro can have multiple rules, similar to match arms, but it matches on Rust syntactic elements instead, with types, expressions, blocks of code, and so on. Here we only have one rule and it matches against a single type since we use :ty. The part before :ty ($ty) is the name for the element that was matched. Inside the curly brackets, after the => symbol, we see the actual code that will be generated. It is the same as our previous implementation of BitSet for u64, except that it uses the meta-variable $ty instead of u64.

To avoid a lot of boilerplate code, we can then use this macro as follows:

int_bitset!(i32);
int_bitset!(u8);
int_bitset!(u64);
主站蜘蛛池模板: 班戈县| 武胜县| 城步| 邵东县| 湟源县| 吐鲁番市| 洪洞县| 增城市| 德格县| 浦县| 乐业县| 合山市| 泰宁县| 壶关县| 淳安县| 南陵县| 阜南县| 五寨县| 油尖旺区| 桃园县| 嵩明县| 犍为县| 扶绥县| 尉氏县| 丽江市| 花垣县| 东丰县| 军事| 美姑县| 吉安市| 斗六市| 临邑县| 昌平区| 江达县| 肃宁县| 湖口县| 遵义县| 襄垣县| 阜南县| 呼玛县| 息烽县|