1 个不稳定版本
0.1.0 | 2023年5月31日 |
---|
#2962 在 Rust 模式
8KB
57 行
const_map
定义一个常量映射和一个关联的常量查找函数。
当使用时,如果查找函数的参数是常量,整个查找将在编译时完成,并用结果常量替换。
如果参数不是常量,它仍然可以工作,但效率不如普通映射,因为查找只是迭代映射的所有元素。
请注意,由于 Rust 标准库和编译器的当前限制,键类型需要是整数类型、bool 或 char,因为其他类型尚未以 const 方式实现 PartialEq
。
示例
use const_map::const_map;
struct Fruits {
name: String,
}
impl Fruits {
const_map!(MAP, get(), (char => &'static str) {
'a' => "apple",
'b' => "banana",
'c' => "clementine",
'd' => "durian",
});
fn new(name: &str) -> Self {
if let Some(s) = Self::get(name.chars().next().expect("shouldn't be empty")) {
Self { name: s.to_owned() }
} else {
Self { name: name.to_owned() }
}
}
}
assert_eq!(Fruits::new("bread").name, "banana");
assert_eq!(Fruits::new("kiwi").name, "kiwi");
// Because the lookup is a `const fn`, it can be used with generic consts:
struct MyFruit<const C: char> {
count: u64,
}
impl<const C: char> MyFruit<C> {
const NAME: &'static str = match Fruits::get(C) {
Some(s) => s,
None => panic!("no fruit found"),
};
pub fn desc(&self) -> String {
format!("{} {}", self.count, Self::NAME)
}
}
let f = MyFruit::<'d'> { count: 42 };
assert_eq!(f.desc(), "42 durian");