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
In newer versions of Rust, the error is
error[E0507]: cannot move out of `*line` which is behind a shared reference
--> src/main.rs:31:33
|
31 | for current_char in line.into_bytes().iter() {
| ^^^^ move occurs because `*line` has type `std::string::String`, which does not implement the `Copy` trait
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?
.bytes()
method.) – huon.as_bytes()
– blussas_bytes()
without cloning. But I still don't understand why ? – PeekmoString
gets thebytes
method fromstr
. – huon