我正在做 Rustlings exercises并且有一个练习“move_semantics3.rs”:
// move_semantics3.rs
// Make me compile without adding new lines-- just changing existing lines!
// (no lines with multiple semicolons necessary!)
// Scroll down for hints :)
pub fn main() {
let vec0 = Vec::new();
let mut vec1 = fill_vec(vec0);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
提示说:
The difference between this one and the previous ones is that the first line of
fn fill_vec
that hadlet mut vec = vec;
is no longer there. You can, instead of adding that line back, addmut
in one place that will change an existing binding to be a mutable binding instead of an immutable one :)
我不知道如何通过只添加一个 mut
来更正此代码。
最佳答案
如果您将代码复制/粘贴到 Playground 上,编译器会报错:
error[E0596]: cannot borrow immutable argument `vec` as mutable
--> src/main.rs:20:5
|
19 | fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
| --- consider changing this to `mut vec`
20 | vec.push(22);
| ^^^ cannot borrow mutably
编译器说明了一切:你必须用 mut vec
替换 vec
因为默认情况下 Rust 变量是不可变的。
关于rust - 如何解决 RuSTLings 练习 "move_semantics3.rs"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50467621/