First of all: I really find it puzzling that my previous question gets closed and a hint pops up: "when to use drain vs into_iter" - that was not my question at all. So I repeat it here - with the hope that it will be read carefully:
I am struggling to learn the ownership concept! of Rust. On the one hand, I learned that each value has a single owner and that a vector owns its elements. Hence let v = vec![1,2,3]; let t = v[1]
should invalidate the vector v
.
However if this is true, I struggle to understand the following excerpt from the book Programming Rust:
.. provide a drain method that takes a mutable reference to the collection and returns an iterator that passes ownership of each element to the consumer.
It then goes on to say
Unlike the into_iter() method, which takes the collection by value and consumes it, drain merely borrows a mutable ref to the collection.
In the example given:
let mut outer = "Earth".to_string();
let inner = String::from_iter(outer.drain(1..4));
assert_eq!(outer,"Eh");
one clearly sees that outer is still usable as a variable after the call of drain.
My question: Isn't this a contradiction? That is, if drain "returns an iterator that passes ownership of each element to the consumer", then we essentially have something like that the ownership of each element is passed to the String::from_iter
function. This is analog to an assignment like let t=v[1]
, so I do not understand why I can still use outer afterwards if some elements of outer have been consumed in the function call.
EDIT: For a better explanation of my question: If something passes ownership of the elements of a string/vector. Then the vector/string is not anymore the owner. So how can it be used later on - it should be invalid to use it, because the ownership was moved.
EDIT2: Please read my question carefully: I do not want to know what drain does and when to use it. I just want to understand the ownership system better and therefore need an explanation for as to why there is no contradiction between the stated description and the use of outer after calling drain()