如何根据另一个函数修改结构的值?

问题描述 投票:0回答:0

我有一个结构,其中包含一个 f32 的 Vec:

struct MyStruct(Vec<f32>);

我想在

MyStruct
上实现2个功能:

  1. 一个返回 f32 但 needs 借用自己
  2. 另一个根据第一个函数返回的值更改存储的 f32
impl MyStruct {
    fn hello(&self) -> f32 {
        0.0  // Just for the example, but the function needs to borrow &self
    }
    
    fn problem(&mut self) {
        for number in &mut self.0 {
            *number = self.hello();
        }
    }
}

我的目标是把MyStruct里面的Vec中的f32改成

hello
返回的值。

然而,借款检查员告诉我:

cannot borrow `*self` as immutable because it is also borrowed as mutable
for number in &mut self.0 {
-----------
|
mutable borrow occurs here
mutable borrow later used here
*number = self.hello();
^^^^^^^^^^^^ immutable borrow occurs here

我期待它,但我没有看到任何其他方法。

我试图不使用借用或可变变量,但它没有用。 任何帮助将不胜感激:)

rust borrow-checker
© www.soinside.com 2019 - 2024. All rights reserved.