rust - 重新借用嵌套的可变引用
问题描述
我正在尝试创建对可变引用的可变引用,删除外部引用,然后重用内部引用。但是,我总是遇到某种错误。这是该问题的一个最小化,非常冗长的示例:
#[derive(Clone, Debug)]
struct NoCopy;
fn foo<'a>(vec: &'a mut Vec<NoCopy>) -> &'a mut NoCopy {
{
let try_first: Option<&'a mut NoCopy> = vec.first_mut();
if let Some(first) = try_first {
return first;
}
}
vec.push(NoCopy);
vec.first_mut().unwrap()
}
这会产生以下错误:
error[E0499]: cannot borrow `*vec` as mutable more than once at a time
--> src/lib.rs:12:5
|
4 | fn foo<'a>(vec: &'a mut Vec<NoCopy>) -> &'a mut NoCopy {
| -- lifetime `'a` defined here
5 | {
6 | let try_first: Option<&'a mut NoCopy> = vec.first_mut();
| ---------------------- --- first mutable borrow occurs here
| |
| type annotation requires that `*vec` is borrowed for `'a`
...
12 | vec.push(NoCopy);
| ^^^ second mutable borrow occurs here
error[E0499]: cannot borrow `*vec` as mutable more than once at a time
--> src/lib.rs:13:5
|
4 | fn foo<'a>(vec: &'a mut Vec<NoCopy>) -> &'a mut NoCopy {
| -- lifetime `'a` defined here
5 | {
6 | let try_first: Option<&'a mut NoCopy> = vec.first_mut();
| ---------------------- --- first mutable borrow occurs here
| |
| type annotation requires that `*vec` is borrowed for `'a`
...
13 | vec.first_mut().unwrap()
| ^^^ second mutable borrow occurs here
无论我尝试什么,我似乎都无法编译它。我认为这个问题可能与为什么我不能在将 &mut 引用传递给接受泛型类型的函数后重用它?,但我无法弄清楚如何将公认的解决方案应用于此问题。这让我想知道这个错误是否真的是正确的行为(即我的代码是不安全的),但我似乎无法找出代码的任何问题。
我如何让这段代码编译,或者编译器错误是由实际的逻辑问题引起的?
解决方案
推荐阅读
- visual-studio - 我无法找到我的应用程序的位置下拉菜单(自动完成)。下面给出代码
- c# - 需要一些关于结合两个类的帮助
- c# - Selenium C# 在输入之前将光标设置为输入的结尾
- r - 如何在 R 中具有多个标题行的 flextable 中设置标题标签?
- encoding - 在 DataWeave mule 4 中编码重音字母
- git - SourceTree - 在 Unstaged 文件部分标记为“丢失”的文件 - 无法摆脱它们
- php - 为什么我的数据库仍然显示 2147483647 错误?
- javascript - 从查询到mysql数据库的cookie中的条目问题
- macros - 在 guile 方案中,如何防止从另一个宏调用宏时重命名?
- python - 自动完成在 git hook 中不起作用,tty 问题?