rust 如何在不可变函数之后执行可变函数?

jogvjijk  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在创建一个虚拟机,并尝试从堆栈中取出两个项目。它按以下顺序执行:

PEEK (Get value),
TAKE (Erase from stack),
PEEK (Get value beneath previous value)

然而,我遇到了一个错误:

error[E0502]: cannot borrow `self.plate` as mutable because it is also borrowed as immutable
   --> src/machine/mod.rs:398:17
    |
397 |                 let apple = self.plate.peek();
    |                             ----------------- immutable borrow occurs here
398 |                 self.plate.take();
    |                 ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
...
401 |                     int: apple.value.int,
    |                          --------------- immutable borrow later used here

一直在寻找修复程序...但是,我找不到解决这个问题的方法。下面是我的代码:
(机器/mod.rs):

MERGE => {
    let apple = self.plate.peek();
    self.plate.take();
    let banana = self.plate.peek();
    let seasoning = GetValueOfType {
        int: apple.value.int,
        float: 0.0,
        str: banana.value.str.clone(),
    };

    let edible = PackedIngredients {
        istype: SupportedTypes::Int,
        value: seasoning,
    };
}

(板块/mod.rs)
第一个

  • (印版只是堆栈)*

尝试使用peek函数&mut self,但这会产生更多问题,因为在给定区域中只能有一个可变变量。
学习各种在线指南,借用,immuts,muts,但没有找到任何适合/解决我的问题.

ecbunoof

ecbunoof1#

你在这里借用了一个不变的词:

let apple = self.plate.peek();

这是因为你取了一个对self &self的不可变引用,并返回&Food,借用检查器并不聪明,无法判断出&Food不属于&self,只能假设你借用了&self的一部分。
然后您尝试使用mutate self.plate,这里的问题是在您使用apple引用int: apple.value.int之后,这意味着apple不能被删除,直到该行,这导致了错误。
此问题有2种解决方案:

Return the struct itself and not a reference
pub fn peek(&self) -> Food { return self.area.last().unwrap(); }

或者,在调用self.plate.peek()之前先删除apple

let apple = self.plate.peek();
// since integer is a Copy then this will copy the int value
let int = apple.value.int;
// `apple` will be dropped here since it is no longer use after
self.plate.take();
let banana = self.plate.peek();
let seasoning = GetValueOfType {
    int,
    float: 0.0,
    str: banana.value.str.clone(),
};

相关问题