gpt4 book ai didi

rust - 借来的可变类型

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

具有借来的可变引用的函数如何调用具有相同借来的可变引用的第二个函数?

fn main() {
let mut a = vec![0, 1, 2, 3, 4];

first_function(&mut a);

println!("{:?}", a);
}

fn first_function(a: &mut Vec<i32>) {
println!("...first function");
a[0] = 5;
second_function(&mut a);
}

fn second_function(a: &mut Vec<i32>) {
println!("...second function");
a[2] = 6;
}
编译器错误通常非常有帮助,但我不明白这一点。
error[E0596]: cannot borrow `a` as mutable, as it is not declared as mutable
--> src/main.rs:12:21
|
9 | fn first_function(a: &mut Vec<i32>) {
| - help: consider changing this to be mutable: `mut a`
...
12 | second_function(&mut a);
| ^^^^^^ cannot borrow as mutable
...这是 Rust Playground中代码的链接

最佳答案

通过编写&mut a,您试图获取对a的可变引用,而不是对其值引用的可变引用,而是&mut &mut Vec<i32>a的值已经是您想要的可变引用:

second_function(a);
updated playground

关于rust - 借来的可变类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62628414/

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