我不明白这个错误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);
}
Run Code Online (Sandbox Code Playgroud)
产生错误:
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
Run Code Online (Sandbox Code Playgroud)
我通过克隆解决了这个问题line:
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() {
| ^^^^ …Run Code Online (Sandbox Code Playgroud) 在这种情况下,错误意味着什么:
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
v[v[1]] = 999;
}
Run Code Online (Sandbox Code Playgroud)
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
v[v[1]] = 999;
}
Run Code Online (Sandbox Code Playgroud)
我发现索引是通过Index和IndexMut特性实现的,这v[1]是*v.index(1). 有了这些知识,我尝试运行以下代码:
use std::ops::{Index, IndexMut};
fn main() {
let mut v: Vec<usize> = vec![1, 2, 3, 4, 5];
*v.index_mut(*v.index(1)) = 999;
}
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,这完美无缺!为什么第一个片段不起作用,但第二个片段起作用?我理解文档的方式,它们应该是等效的,但显然情况并非如此。
我有以下代码:
pub struct Canvas<'a> {
width: isize,
height: isize,
color: Color,
surface: Surface,
texture: Texture,
renderer: &'a Renderer,
}
impl<'a> Canvas<'a> {
pub fn new(width: isize, height: isize, renderer: &'a Renderer) -> Canvas<'a> {
let color = Color::RGB(0, 30, 0);
let mut surface = core::create_surface(width, height);
let texture = Canvas::gen_texture(&mut surface, width, height, color, renderer);
Canvas {
width: width,
height: height,
color: color,
surface: surface,
texture: texture,
renderer: renderer,
}
}
pub fn color(&mut self, color: Color) -> &mut Canvas<'a> …Run Code Online (Sandbox Code Playgroud)