临时值在此语句结束时被释放 [英] Temporary value is freed at the end of this statement
问题描述
我正在尝试使用 Select crate 抓取网页:
I'm trying to scrape a webpage using the Select crate:
let document = Document::from_read(response).unwrap();
for node in document.find(Class("lia-list-row")) {
let title = node.find(Class("page-link")).next().unwrap();
let title_text = title.text().trim();
println!("{}
", title_text);
}
导致以下错误:
let title_text = title.text().trim();
^^^^^^^^^^^^ - temporary value is freed at the end of this statement
|
creates a temporary which is freed while still in use
println!("{} - {}
", i, title_text);
---------- borrow used here, in later iteration of loop
我通过分离 .text()
和 .trim()
let title_text = title.text();
let trim_text = title_text.trim();
有什么区别?为什么第一次尝试失败?
What is the difference? Why did the first attempt fail?
推荐答案
这个乍一看似乎很复杂,但请记住 String
和 &str
是不同的野兽.
This one seems convoluted at first, but remember that String
and &str
are different beasts.
String
可以独立存在和使用,但 &str
只是对 String
的一部分的引用.因此,&str
的生命周期与引用的 String
生命周期一样长.让我们看看它应该如何处理返回签名.
String
can live and be used on its own, but &str
is just a reference to part of String
. So, &str
can live as long as referenced String
lives. Lets see how it should work on return signatures.
let title_text = title .text() .trim();
// ^ ^ ^
// Node String <- &str
这里,
title
是一个select::Node
.
节点::text
返回一个 String
,但没有将其绑定到上下文.
Node::text
returns a String
, but nothing binds it to context.
String::trim
反过来返回一个 &str
,它是对 String
本身的一部分的引用.
String::trim
, in turn, returns a &str
which is a reference to part of String
itself.
最后,借用检查器只是不明白它应该如何处理对 String
的引用,因为它是一个临时值(非绑定).
In the end, the borrow checker just doesn't understand how it should process a reference to String
that will not live long enough in context, as it is a temporary value (non-bound).
这篇关于临时值在此语句结束时被释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!