【发布时间】:2016-08-25 15:39:30
【问题描述】:
我想使用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) {
^~~~~~~~
我很难过,我需要做一些类型转换吗?
【问题讨论】:
-
您可以添加
// put stuff in refs部分吗?这实际上或多或少对这个问题很重要。 -
请添加一个完整的例子我们可以尝试编译。听起来你有一个
HashSet<&str>而不是HashSet<String>,正如@LukasKalbertodt 所说,这取决于你如何初始化refs。 -
@LukasKalbertodt 我在插入字符串的地方添加了。所以我认为在
HashSet初始化时我需要做的更多... -
@ray no 初始化没问题,但找出一些事情很重要。看看我的回答就明白我的意思了:)
标签: string rust hashset borrowing