gpt4 book ai didi

rust - 在 for 循环中处理 "borrowed value does not live long enough"

转载 作者:行者123 更新时间:2023-12-03 11:42:04 24 4
gpt4 key购买 nike

<分区>

我正在抓取的网站要求我查询 HTML 页面的标题标签以及一些其他元素,以查看我是否可以辨别文章的标题。

我创建了一个 HashMap<&str, u8> 并立即 .insert(title_tag_text, 1) ,查询标题元素,然后我希望将标题标签的文本类似地插入到 HashMap 中,但我得到错误 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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com