0
fn extract_html(url: &str) -> Html {
    let response = reqwest::blocking::get(url).unwrap().text().unwrap();
    return scraper::Html::parse_document(&response);
}

fn get_all_links(url: &str) -> Vec<&str> {
    let mut links: Vec<&str> = vec![];
    let link_html: Html = extract_html(url);
    let link_selector = Selector::parse("a.list-chapter").unwrap();
    for element in link_html.select(&link_selector) {
        links.push(element.value().attr("href").unwrap() as &str);
    }
    links
}

I'm very new to Rust and I'm attempting to return a vector of href values from a given url, but I'm getting the error "returns a value referencing data owned by the current function" referring to borrowing link_html in

link_html.select(&link_selector)

is there any way to parse the elements without borrowing from a local variable, or any other way to resolve this issue? Preferably without leaking memory for future reference, though it doesn't particularly matter in this case.

  • 1
    As a short answer: Return `Vec` (and convert the `&str`s with `.to_owned()`). A long answer can probably be found in the duplicates [here](https://stackoverflow.com/questions/29428227/return-local-string-as-a-slice-str) or [here](https://stackoverflow.com/questions/29781331/why-cant-i-return-an-str-value-generated-from-a-string). Also, as a rule of thumb if you're new to Rust: Avoid `&` in struct fields and return values for a while. It'll save you from many borrow checker errors while you get used to the rest of the language. – Caesar Nov 10 '22 at 07:07

0 Answers0