I just had a random thought: a common pattern in Rust is to things such as:

let vec_a: Vec<String> = /* ... */;
let vec_b: Vec<String> = vec_a.into_iter().filter(some_filter).collect();

Usually, we need to be aware of the fact that Iterator::collect() allocates for the container we are collecting into. But in the snippet above, we’ve consumed a container of the same type. And since Rust has full ownership of the vector, in theory the memory allocated by vec_a could be reused to store the collected results of vec_b, meaning everything could be done in-place and no additional allocation is necessary.

It’s a highly specific optimization though, so I wonder if such a thing has been implemented in the Rust compiler. Anybody who has an idea about this?

  • arendjrOP
    link
    fedilink
    arrow-up
    1
    ·
    7 months ago

    The composability doesn’t have much to do with whether it’s a reference or a move, it’s because it bypasses usage of the Iterator methods. Iterators chains can consist of filter, map and other operations, which allows various functions and/or closures to be composed together. Whereas with retain_mut() there isn’t really a chain and functions you may otherwise use in an iterator chain become harder to (re)use.