#const #lookup #context #defined #map #sorting #key

const_lookup_map

Rust中可以在const上下文中定义的map

1个不稳定版本

0.1.0 2023年2月23日

#2099 in 算法

无许可证

8KB
136

const_lookup_map

Rust中可以在const上下文中定义的map。

有两种方式创建它

use const_lookup_map::{ConstLookup, lookup};

const LOOKUP_MACRO: ConstLookup<3, &str, &str> = lookup! {
    "best" => "better",
    "test" => "testing",
    "guessed" => "guessing",
};
use const_lookup_map::ConstLookup;

pub const LOOKUP: ConstLookup<4, &str, &str> = ConstLookup::new(
    ["bye", "hallo", "hey", "test"],
    [
        "bye.example.com",
        "hallo.example.com",
        "hey.example.com",
        "test.example.com",
    ],
);

注意:键应该是有序的/排序的,因为get方法将使用这个来有效地获取值。参见 ConstLookup::check_sorted

用法

use const_lookup_map::{ConstLookup, lookup};

const LOOKUP: ConstLookup<3, &str, &str> = lookup! {
    "best" => "better",
    "test" => "testing",
    "guessed" => "guessing",
};

fn my_function() {
  assert_eq!(LOOKUP.get(&"best"), Some(&"better"));
  assert_eq!(LOOKUP[&"best"], "better");
}

无运行时依赖