我想要使用HashSet
进行快速的字符串查找,但是在不引起编译错误的情况下,我似乎找不到一种将字符串变量传递给contains
方法的方式。
refs = HashSet::new();
let first_pass = link_regex.replace_all(&buffer, |caps: &Captures| {
if caps.len() == 2 {
refs.insert(caps.at(2).unwrap());
}
caps.at(1).unwrap().to_owned()
});
let out = ref_regex.replace_all(&first_pass, |caps: &Captures| {
let capture = caps.at(1).unwrap().to_owned();
// only remove if we've seen it before
if refs.contains(capture) {
return "".to_string();
}
capture
});
这会导致出现错误:
src/bin/remove_links.rs:30:26: 30:33 error: mismatched types [E0308]
src/bin/remove_links.rs:30 if refs.contains(capture) {
^~~~~~~
src/bin/remove_links.rs:30:26: 30:33 help: run `rustc --explain E0308` to see a detailed explanation
src/bin/remove_links.rs:30:26: 30:33 note: expected type `&_`
src/bin/remove_links.rs:30:26: 30:33 note: found type `std::string::String`
如果我尝试
refs.contains(&capture)
然后我得到了
src/bin/remove_links.rs:30:17: 30:25 error: the trait bound `&str: std::borrow::Borrow<std::string::String>` is not satisfied [E0277]
src/bin/remove_links.rs:30 if refs.contains(&capture) {
^~~~~~~~
我被卡住了,我需要进行某种类型转换吗?
// 把东西放在 refs 里
这部分吗?对于这个问题来说,它实际上是更重要的。 - Lukas KalbertodtHashSet <&str>
而不是HashSet <String>
,这可能是由于您如何初始化refs
引起的。 - Chris EmersonHashSet
初始化时还需要做更多的事情... - ray