简体   繁体   中英

In Rust, what is the best way to return an iterator that has a lifetime dependency?

I'm using the select library to parse an HTML table into a stream of Data structures.

Ideally I would like to write a function that downloads the HTML, parses it and returns an iterator. Something like this:

fn get_data_iterator(...) -> impl Iterator<Data> {
    let doc = Document::from_read(...).unwrap();
    doc.find(Name("tr")).map(tr_to_data)
}

However, doc.find() returns an Find<'a, P> which is bound to the lifetime of doc .

Is there a way to package doc with the returned iterator so that it lives as long as the iterator?

I tried writing a proxy iterator struct that would contain both doc and the iterator created with doc.find , but I couldn't find a way to do that correctly.

If you control the interface, you can provide the Document as an argument to get_data_iterator , then the lifetime of the impl Iterator<Data> can be tied to the reference that you're passing into this method, ie:

// lifetimes could be elided, annotation for demonstration purposes
fn get_data_iterator<'a>(doc: &'a Document, ...) -> impl Iterator<Item=Data> + 'a {
    doc.find(Name("tr")).map(tr_to_data)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM