gpt4 book ai didi

rust - 克隆一个 mut 引用以便在其他地方使用 mut 引用

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

<分区>

我在使用函数时遇到错误,因为借用一个可变的,如果还有一个不可变的借用,就像多次借用一个可变的一样是不允许的。

pub fn _function(list: &mut Vec<char>) {
for (n, c) in list.iter().enumerate() {
if *c == ' ' {
list.remove(n);
}
}
}
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
--> src/lib.rs:4:14
|
2 | for (n, c) in list.iter().enumerate() {
| -----------------------
| |
| immutable borrow occurs here
| immutable borrow later used here
3 | if *c == ' ' {
4 | list.remove(n);
| ^^^^^^^^^^^^^^ mutable borrow occurs here

我遇到的唯一解决方案是克隆列表

pub fn _function(list: &mut Vec<char>) {
for (n, c) in list.clone().iter().enumerate() {
if *c == ' ' {
list.remove(n);
}
}
}

我想知道是否有任何其他解决方案可以在不克隆 list 和使用更多内存的情况下使用这两个函数。

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