相关疑难解决方法(0)

无法摆脱借来的内容

我不明白这个错误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)

reference move-semantics rust borrow-checker

115
推荐指数
2
解决办法
6万
查看次数

尝试转让所有权时,无法摆脱借来的内容

我正在编写一个链表来包围Rust的生命周期,所有权和引用.我有以下代码:

pub struct LinkedList {
    head: Option<Box<LinkedListNode>>,
}

pub struct LinkedListNode {
    next: Option<Box<LinkedListNode>>,
}

impl LinkedList {
    pub fn new() -> LinkedList {
        LinkedList { head: None }
    }

    pub fn prepend_value(&mut self) {
        let mut new_node = LinkedListNode { next: None };

        match self.head {
            Some(ref head) => new_node.next = Some(*head),
            None => new_node.next = None,
        };

        self.head = Some(Box::new(new_node));
    }
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

但是我收到以下编译错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:18:52
   |
18 | …
Run Code Online (Sandbox Code Playgroud)

reference move-semantics rust borrow-checker

14
推荐指数
1
解决办法
9775
查看次数

无法摆脱Rust中的借来的内容

pub struct Character {
    name: String,
    hp: i32,
    level: i32,
    xp: i32,
    xp_needed: i32,
    gold: i32
}

impl Character {
    pub fn new(name: String) -> Character {
        let mut rng = thread_rng();

        let hp: i32 = rng.gen_range(12, 75);
        let gold: i32 = rng.gen_range(10, 50);

        Character { name: name, hp: hp, level: 1, xp: 0, gold: gold, xp_needed: 100 }
    }

    pub fn get_name(&self) -> String {
        self.name
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我到底是怎么违反规则的呢?

在高层次上,这对Rust来说是违规的.你不能转让借来的东西的所有权,因为你不拥有它.

嗯,不是吗?我有其他功能,如:

pub fn get_hp(&self) -> i32 { …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
5979
查看次数

标签 统计

rust ×3

borrow-checker ×2

move-semantics ×2

reference ×2