这可能不是Rust特有的,虽然它是我目前关注的语言.
我正在编写一个函数来将语言(MySQL)解析为标记并以格式化方式输出它们,其中一部分包括查找当前工作标记以查看它是名称,函数还是列/表名称.
目前,我正在使用匹配语句
pub fn is_word(word: &str) -> bool {
match word {
"accessible"
| "account"
| "action"
| "active"
| "add"
// ...
| "year"
| "year_month"
| "zerofill" => true,
_ => false,
}
}
Run Code Online (Sandbox Code Playgroud)
在实际列表是非常非常长.
这是解决这个问题的最好方法吗?我已经使用尝试HashMap,以及用.contains_key(),但这是非常慢
我的HashMap实现看起来像这样:
use std::collections::HashMap;
lazy_static! {
static ref words: HashMap<&'static str, u8> = hashmap!{
"accessible" => 0,
"account" => 0,
"action" => 0,
"active" => 0,
"add" => 0,
// ...
"year" => 0,
"year_month" => 0,
"zerofill" => 0,
};
}
pub fn is_word(word: &str) -> bool {
words.contains_key(word)
}
Run Code Online (Sandbox Code Playgroud)
由于您的列表在编译时是固定的,因此请使用完美的哈希值,例如phf crate提供的哈希:
build.rs
extern crate phf_codegen;
use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
fn main() {
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
let mut file = BufWriter::new(File::create(&path).unwrap());
write!(&mut file, "static KEYWORDS: phf::Set<&'static str> = ").unwrap();
phf_codegen::Set::new()
.entry("accessible")
.entry("account")
.entry("action")
.entry("active")
.entry("add")
// ...
.entry("year")
.entry("year_month")
.entry("zerofill")
.build(&mut file)
.unwrap();
write!(&mut file, ";\n").unwrap();
}
Run Code Online (Sandbox Code Playgroud)
SRC/main.rs
extern crate phf;
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
pub fn is_word(word: &str) -> bool {
KEYWORDS.contains(word)
}
Run Code Online (Sandbox Code Playgroud)
根据您提供的基准测试代码,这至少同样快.