What's the most efficient way to reuse an iterator in Rust?

前端 未结 3 406
花落未央
花落未央 2020-12-20 13:55

I\'d like to reuse an iterator I made, so as to avoid paying to recreate it from scratch. But iterators don\'t seem to be cloneable and collect mov

3条回答
  •  Happy的楠姐
    2020-12-20 14:29

    Iterators in general are Clone-able if all their "pieces" are Clone-able. You have a couple of them in my_iter that are not: the anonymous closures (like the one in flat_map) and the ToUppercase struct returned by to_uppercase.

    What you can do is:

    1. rebuild the whole thing (as @ArtemGr suggests). You could use a macro to avoid repetition. A bit ugly but should work.
    2. collect my_iter into a Vec before populating my_struct (since you seem to collect it anyway in there): let my_iter: Vec = my_string.unwrap_or("A").chars().flat_map(|c|c.to_uppercase()).map(|c| Tag::from(c).unwrap() ).collect();
    3. create your own custom iterator. Without your definitions of my_string (since you call unwrap_or on it I assume it's not a String) and Tag it's hard to help you more concretely with this.

提交回复
热议问题