I don't understand the error cannot move out of borrowed content
. I have received it many times and I have always solved it, but I've never understood why.
For example:
for line in self.xslg_file.iter() {
self.buffer.clear();
for current_char in line.into_bytes().iter() {
self.buffer.push(*current_char as char);
}
println!("{}", line);
}
produces the error:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:31:33
|
31 | for current_char in line.into_bytes().iter() {
| ^^^^ cannot move out of borrowed content
I solved it by cloning line
:
for current_char in line.clone().into_bytes().iter() {
I don't understand the error even after reading other posts like:
- Can't borrow File from &mut self (error msg: cannot move out of borrowed content)
- Changing a node in a tree in Rust
What is the origin of this kind of error?
Let's look at the signature for
into_bytes
:This takes
self
, not a reference to self (&self
). That means thatself
will be consumed and won't be available after the call. In its place, you get aVec<u8>
. The prefixinto_
is a common way of denoting methods like this.I don't know exactly what your
iter()
method returns, but my guess is that it's an iterator over&String
, that is, it returns references to aString
but doesn't give you ownership of them. That means you cannot call a method that consumes the value.As you've found, one solution is to use
clone
. This creates a duplicate object that you do own, and can callinto_bytes
on. As other commenters mention, you can also useas_bytes
which takes&self
, so it will work on a borrowed value. Which one you should use depends on your end goal for what you do with the pointer.In the larger picture, this all has to do with the notion of ownership. Certain operations depend on owning the item, and other operations can get away with borrowing the object (perhaps mutably). A reference (
&foo
) does not grant ownership, it's just a borrow.Transferring ownership is a useful concept in general - when I am done with something, someone else may have it. In Rust, it's a way to be more efficient. I can avoid allocating a copy, giving you one copy, then throwing away my copy. Ownership is also the most permissive state; if I own an object I can do with it as I wish.
Here's the code that I created to test with: