相关疑难解决方法(0)

无法从&mut self借用文件(错误信息:无法移出借来的内容)

use std::fs::File;
use std::io::Read;

pub struct Foo {
    maybe_file: Option<File>,
}

impl Foo {
    pub fn init(&mut self) {
        self.maybe_file = Some(File::open("/proc/uptime").unwrap());
    }

    pub fn print(&mut self) {
        let mut file = self.maybe_file.unwrap();
        let mut s = String::new();
        file.read_to_string(&mut s).unwrap();
        println!("Uptime: {}", s);
    }
}

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

编译这将给我:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:14:24
   |
14 |         let mut file = self.maybe_file.unwrap();
   |                        ^^^^ cannot move out of borrowed content
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我该怎么做才能解决它?

rust borrow-checker

18
推荐指数
1
解决办法
5748
查看次数

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

我正在编写一个链表来包围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进行手动锁定

我正在尝试在Rust中编写union-find的实现.这在C语言中实现非常简单,同时仍然具有复杂的运行时分析.

我无法获得Rust的互斥锁语义以允许迭代的手动锁定.

这就是我现在所处的位置.

首先,这是我在C中想要的部分结构的一个非常简单的实现:

#include <stdlib.h>

struct node {
  struct node * parent;
};

struct node * create(struct node * parent) {
  struct node * ans = malloc(sizeof(struct node));
  ans->parent = parent;
  return ans;
}

struct node * find_root(struct node * x) {
  while (x->parent) {
    x = x->parent;
  }
  return x;
}

int main() {
  struct node * foo = create(NULL);
  struct node * bar = create(foo);
  struct node * baz = create(bar);
  baz->parent = find_root(bar);
} …
Run Code Online (Sandbox Code Playgroud)

locking rust data-structures

9
推荐指数
1
解决办法
1556
查看次数