不能借为不可变的,因为它也被借为可变的 [英] cannot borrow as immutable because it is also borrowed as mutable

查看:37
本文介绍了不能借为不可变的,因为它也被借为可变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用库中的结构 FooBar,但在客户端代码中出现编译错误.我将代码简化为:

I'm using the structs Foo and Bar from a library and I'm getting a compilation error in the client code. I simplified the code to this:

use std::marker::PhantomData;

struct Foo {
    some_str: &'static str,
}

struct Bar<'a> {
    some_str: &'static str,
    marker: PhantomData<&'a Foo>,
}

impl Foo {
    fn read_data(&self) {
        // add code here
    }
    fn create_bar<'a>(&'a mut self) -> Bar<'a> {
        Bar {
            some_str: "test2",
            marker: PhantomData,
        }
    }
}

fn process(_arr: &mut [Bar]) {}

fn main() {
    let mut foo = Foo { some_str: "test" };
    let mut array: [Bar; 1] = [foo.create_bar()];
    process(&mut array);
    foo.read_data();
}

(游乐场)

输出:

error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
  --> src/main.rs:30:5
   |
28 |     let mut array: [Bar; 1] = [foo.create_bar()];
   |                                --- mutable borrow occurs here
29 |     process(&mut array);
30 |     foo.read_data();
   |     ^^^ immutable borrow occurs here
31 | }
   | - mutable borrow ends here

控制台输出中的错误很清楚,但我无法解决问题.

The error in the console output is very clear, but I cannot fix the problem.

推荐答案

您可以限制 array 变量的生命周期,方法是将其放置在带有花括号 ({ ...}):

You can limit the lifetime of the array variable by placing it in a new scope with curly braces ({ ... }):

fn main() {
    let mut foo = Foo { some_str: "test" };
    {
        let mut array: [Bar; 1] = [foo.create_bar()];
        process(&mut array);
    }
    foo.read_data();
}

这篇关于不能借为不可变的,因为它也被借为可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆