我正在做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
}
提示说:
我不知道如何通过仅添加一个
mut
来更正此代码。 最佳答案
如果将代码复制/粘贴到操场上,则编译器会提示:
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
编译器说了一切:您必须用
vec
替换mut vec
,因为默认情况下Rust变量中的变量是不可变的。关于rust - 如何解决RuSTLings练习 “move_semantics3.rs”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50467621/