在尝试重构运行良好的 Rust 应用程序时,我尝试将循环的内容分离到一个新函数中。然而,在这个新重构的函数中,我需要传递一个必须可变的参数,并通过引用传递。突然之间,绝对内联工作的代码仅仅因为可变的引用传递而崩溃了。
我的问题是:有人可以解释一下为什么这样的“简单”更改不起作用吗?(即重构出原本未更改的代码的新函数)
我有一个关于该问题的最小演示,以及下面的一些工作比较。这是该代码的错误:
error[E0499]: cannot borrow `str_to_int` as mutable more than once at a time
--> src/main.rs:30:22
|
30 | get_key(key, &mut str_to_int);
| ^^^^^^^^^^^^^^^ `str_to_int` was mutably borrowed here in the previous iteration of the loop
Run Code Online (Sandbox Code Playgroud)
示例代码:
use std::collections::BTreeMap;
fn get_int (
key: u32,
values: &mut BTreeMap<u32, u32>,
) -> &u32 {
values.entry(key).or_insert_with(|| { 1 })
}
fn get_key<'a> (
key: &'a str,
values: &'a mut BTreeMap<&'a str, u32>,
) -> &'a u32 {
values.entry(key).or_insert_with(|| { 1 …Run Code Online (Sandbox Code Playgroud)