gpt4 book ai didi

rust - 用子切片引用覆盖切片引用时出错

转载 作者:行者123 更新时间:2023-11-29 08:29:29 25 4
gpt4 key购买 nike

我正在尝试确定所有权规则。我想:

  • 从对切片的可变引用开始
  • 对其内容进行一些修改
  • 减少对子切片引用的切片引用并重复

下面是我的尝试:

pub fn example() {
// Make a mutable slice
let mut v = [0, 1, 2, 3];

// Make a mutable reference to said slice
let mut v_ref = &mut v[..];

while v_ref.len() > 1 {
// Involves some edits -> need mut
v_ref.swap(0, v_ref.len() - 1);

// Try to reduce slice to sub-slice (some simplification here)
// Errors!
let (v_l, v_h) = v.split_at_mut(v.len() / 2);
v_ref = v_l;
}
}

但是我得到了错误:

error[E0502]: cannot borrow `*v_ref` as immutable because it is also borrowed as mutable
--> src/lib.rs:11:23
|
11 | v_ref.swap(0, v_ref.len() - 1);
| ----- ^^^^^ - mutable borrow ends here
| | |
| | immutable borrow occurs here
| mutable borrow occurs here

error[E0499]: cannot borrow `v` as mutable more than once at a time
--> src/lib.rs:15:26
|
7 | let mut v_ref = &mut v[..];
| - first mutable borrow occurs here
...
15 | let (v_l, v_h) = v.split_at_mut(v.len() / 2);
| ^ second mutable borrow occurs here
...
18 | }
| - first borrow ends here

error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/lib.rs:15:41
|
7 | let mut v_ref = &mut v[..];
| - mutable borrow occurs here
...
15 | let (v_l, v_h) = v.split_at_mut(v.len() / 2);
| ^ immutable borrow occurs here
...
18 | }
| - mutable borrow ends here

我知道您不能在与单个可变引用相同的范围内对一个对象有多个引用。

应该有一种安全的方法来缩小切片的范围,因为您只是在缩小当前可变引用的范围。最好的方法是什么?

最佳答案

问题 1:可变地和不可变地使用同一个变量

作为Peter Hall points out ,代码尝试引用变量 v,同时存在对它的并发可变引用,即使您不再关心 v_ref。一个 MCVE:

pub fn example() {
let mut v = 0;
let mut v_ref = &mut v;
println!("{}", v)
}

另见:

问题2:可变和不可变地使用同一个变量

然后代码尝试在单个函数调用中重叠可变和可变借用。一个 MCVE:

pub fn example() {
let mut v = [0, 1, 2, 3];
v.split_at_mut(v.len());
}

另见:

问题3:可变地和可变地使用同一个变量

然后代码在循环中重叠了 v 的可变借用。

另见:


一起:

pub fn example() {
let mut v = [0, 1, 2, 3];
let mut v_ref = &mut v[..];

while v_ref.len() > 1 {
let len = v_ref.len();
v_ref.swap(0, len - 1);
let (v_l, _) = { v_ref }.split_at_mut(len / 2);
v_ref = v_l;
}
}

关于rust - 用子切片引用覆盖切片引用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com