我正在抓取的网站要求我查询HTML页面的标题标签以及其他几个元素,以查看是否可以确定文章的标题。
我创建了一个 HashMap<&str, u8>
并立即 .insert(title_tag_text, 1)
,查询标题元素,然后希望以类似的方式将标题标签的文本插入哈希映射表中,但是我收到了错误消息 borrowed value does not live long enough
。
我不确定我是否理解正确,因为我认为我已经正确地将 std::string::String
解引用为 &str
,这应该实现了 Copy
特性?不幸的是,我怀疑我计划实现的下一段代码也有类似的问题。
let mut title_candidates: HashMap<&str, u8> = HashMap::new();
let title_tag_text: String = Selector::parse("title")
.ok()
.and_then(|selector| html_document.select(&selector).next())
.map(|elem| elem.inner_html())?;
title_candidates.insert(&*title_tag_text, 1);
Selector::parse("h1, h2, h3, .title")
.ok()
.as_ref()
.map(|selector| html_document.select(selector))?
.map(|elem| elem.inner_html()) // std::string::String
.for_each(|title| {
*title_candidates.entry(&*title).or_insert(0) += 1;
// if title_tag_text.contains(&*title.as_str()) {
// *title_candidates.entry(&*title_tag_text) += 1;
// }
});
error[E0597]: `title` does not live long enough
--> src/main.rs:140:39
|
125 | let mut title_candidates: HashMap<&str, u8> = HashMap::new();
| -------------------- lifetime `'1` appears in the type of `title_candidates`
...
140 | *title_candidates.entry(&*title).or_insert(0) += 1;
| -------------------------^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `title` is borrowed for `'1`
...
144 | });
| - `title` dropped here while still borrowed