【发布时间】:2015-03-25 08:59:32
【问题描述】:
我不明白错误cannot move out of borrowed content。收到了很多次,一直都解决了,一直不明白为什么。
例如:
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);
}
产生错误:
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
在较新版本的 Rust 中,错误是
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
我通过克隆line解决了这个问题:
for current_char in line.clone().into_bytes().iter() {
即使在阅读其他帖子后我也不明白错误:
- Can't borrow File from &mut self (error msg: cannot move out of borrowed content)
- Changing a node in a tree in Rust
这种错误的根源是什么?
【问题讨论】:
-
你看过questions like this吗? (顺便说一句,字符串提供了
.bytes()方法。) -
是的,我调查过了,但不明白 :( 而且我的字符串是 std::string::String,根据文档,没有 .bytes() 方法
-
它叫
.as_bytes() -
事实上,谢谢,它可以与
as_bytes()一起使用,无需克隆。但我还是不明白为什么? -
String从str获取bytes方法。
标签: reference rust move-semantics borrow-checker