相关疑难解决方法(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万
查看次数

不能借用为不可变的因为它在函数参数中也被借用为可变的

这里发生了什么(游乐场)?

struct Number {
    num: i32
}

impl Number {
    fn set(&mut self, new_num: i32) {
        self.num = new_num;
    }
    fn get(&self) -> i32 {
        self.num
    }
}

fn main() {
    let mut n = Number{ num: 0 };
    n.set(n.get() + 1);
}
Run Code Online (Sandbox Code Playgroud)

给出了这个错误:

error[E0502]: cannot borrow `n` as immutable because it is also borrowed as mutable
  --> <anon>:17:11
   |
17 |     n.set(n.get() + 1);
   |     -     ^          - mutable borrow ends here
   |     |     |
   |     | …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

21
推荐指数
1
解决办法
3400
查看次数

不能借用可变性,因为它也被借用为不可变的

我正在学习Rust,我不明白为什么这不起作用.

#[derive(Debug)]
struct Node {
    value: String,
}

#[derive(Debug)]
pub struct Graph {
    nodes: Vec<Box<Node>>,
}

fn mk_node(value: String) -> Node {
    Node { value }
}

pub fn mk_graph() -> Graph {
    Graph { nodes: vec![] }
}

impl Graph {
    fn add_node(&mut self, value: String) {
        if let None = self.nodes.iter().position(|node| node.value == value) {
            let node = Box::new(mk_node(value));
            self.nodes.push(node);
        };
    }

    fn get_node_by_value(&self, value: &str) -> Option<&Node> {
        match self.nodes.iter().position(|node| node.value == *value) {
            None => None, …
Run Code Online (Sandbox Code Playgroud)

reference rust

10
推荐指数
2
解决办法
1万
查看次数

标签 统计

rust ×3

borrow-checker ×2

reference ×2

move-semantics ×1