Rust's drain, iterator dropped … “removes any remaining elements”

倖福魔咒の 提交于 2020-01-16 00:46:07

问题


On page 327 of Programming Rust you can find the following statement

However, unlike the into_iter() method, which takes the collection by value and consumes it, drain merely borrows a mutable references to the collection, and when the iterator is dropped, it removes any remaining elements from the collection, and leaves it empty.

I'm confused at what it means it says it removes any remaining elements from the collection? I can see with this code when the iterator is dropped the remaining elements from a are still there,

fn main() {
    let mut a = vec![1, 2, 3, 4, 5];
    {
        let b: Vec<i32> = a.drain(0..3).collect();
    }

    println!("Hello, world! {:?}", a);
}

Perhaps I'm confused at merely the wording. Is there something more to this?


回答1:


This looks like a bit imprecise wording.

The real meaning of these words is: if you drop the drain iterator without exhausting it, it will drop all the elements used for its creation. As you've asked it to use only the first three elements, it won't empty the entire vector, but rather the first part only; but it will do this even if unused:

fn main() {
    let mut a = vec![1, 2, 3, 4, 5];
    {
        let _ = a.drain(0..3);
    }

    println!("Hello, world! {:?}", a);
}
Hello, world! [4, 5]

playground

You could understand this in the following way: the "collection" mentioned here is not the initial collection the drain was called on, but rather is "sub-collection", specified by the passed range.



来源:https://stackoverflow.com/questions/58262902/rusts-drain-iterator-dropped-removes-any-remaining-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!