我不明白这个错误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) 我是Rust的新手,并试图围绕所有权/借款概念.现在我已经将代码缩减到这个给出编译错误的最小代码示例.
pub struct Display {
color: Color,
}
pub enum Color {
Blue = 0x1,
Red = 0x4,
}
impl Display {
fn get_color_value(&self) -> u16 {
self.color as u16
}
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)src/display.rs:12:9: 12:13 error: cannot move out of borrowed content src/display.rs:12 self.color as u16 ^~~~ error: aborting due to previous error Could not compile.
我仍然在所有的东西都被价值心态所复制,在那里它完全合法,self.color因为那会得到我的副本Color.显然,我错了.我在SO上发现了一些关于同样错误的其他问题,但没有解决我的问题.
据我了解,该领域由拥有者的所有者拥有Display.由于我只借用了一个参考Display,我不拥有它.提取color转移Color给我的所有权的尝试,这是不可能的,因为我没有拥有Display.它是否正确?
我该如何解决?
我有一个程序,或多或少看起来像这样
struct Test<T> {
vec: Vec<T>
}
impl<T> Test<T> {
fn get_first(&self) -> &T {
&self.vec[0]
}
fn do_something_with_x(&self, x: T) {
// Irrelevant
}
}
fn main() {
let t = Test { vec: vec![1i32, 2, 3] };
let x = t.get_first();
t.do_something_with_x(*x);
}
Run Code Online (Sandbox Code Playgroud)
基本上,我们在结构上调用一个Test借用某些值的方法.然后我们在同一个struct上调用另一个方法,传递先前获得的值.
这个例子非常好用.现在,当我们制作main泛型的内容时,它不再起作用了.
fn generic_main<T>(t: Test<T>) {
let x = t.get_first();
t.do_something_with_x(*x);
}
Run Code Online (Sandbox Code Playgroud)
然后我收到以下错误:
错误:无法移出借来的内容
src/main.rs:14 let raw_x =*x;
我不完全确定为什么会这样.有人可以向我解释为什么Test<i32>在打电话get_first时不借用Test<T>?
req.url.fragment是可选的String.如果它有一个值,我想将该值复制到其中fragment,否则我想分配一个空字符串.我一直收到错误cannot move out of borrowed content.
我该如何解决这个问题?
fn fb_token(req: &mut Request) -> IronResult<Response> {
let fragment = match req.url.fragment {
Some(fragment) => fragment,
None => "".to_string(),
};
Ok(Response::with((status::Ok, fragment)))
}
Run Code Online (Sandbox Code Playgroud) 我正在学习Rust,我正在与借阅检查员作斗争.
我有一个基本的Point结构.我有一个scale修改点的所有坐标的函数.我想从另一个名为的方法调用此方法convert:
struct AngleUnit;
struct Point {
x: f32,
y: f32,
z: f32,
unit: AngleUnit,
}
fn factor(_from: AngleUnit, _to: AngleUnit) -> f32 {
1.0
}
impl Point {
pub fn new(x: f32, y: f32, z: f32, unit: AngleUnit) -> Point {
Point { x, y, z, unit }
}
fn scale(&mut self, factor: f32) {
self.x *= factor;
self.y *= factor;
self.z *= factor;
}
fn convert(&mut self, unit: AngleUnit) {
let point_unit …Run Code Online (Sandbox Code Playgroud)