I’m trying to collect all links contained in a given http
address into a vector of &str
s, like the following:
extern crate reqwest;
extern crate select;
use select::document::Document;
use select::predicate::Name;
fn extract_links(url: &str) -> Result<Vec<&str>, &str> {
match reqwest::get(url) {
Ok(res) => {
let mut links = vec![];
Document::from_read(res)
.unwrap()
.find(Name("a"))
.filter_map(|a| a.attr("href"))
.for_each(|link| links.push(link));
return Ok(links);
},
Err(_) => { return Err("The app was unable to fetch a url.") }
}
}
This code outputs the following error:
[rustc]
borrowed value does not live long enough
temporary value does not live long enough
note: consider using a `let` binding to increase its lifetime [E0597]
* main.rs(12, 13): temporary value does not live long enough
* main.rs(16, 51): temporary value only lives until here
I’ve noticed that this error only shows up when I try to push the contents of Document::from_read(res). ... .filter_map(|a| a.attr("href"))
into links
. For example, if I replace line 16 for .for_each(|link| println!("{}", link));
, the error is avoided all together.
What am I doing wrong? How could I perform such task?