我正在做Rustlings练习,有一个练习“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
}
Run Code Online (Sandbox Code Playgroud)
提示说:
这个和上一个的区别在于
fn fill_vec,had的第一行已经let mut vec = vec;不存在了。您可以,而不是添加该行,mut在一个地方添加,将现有绑定更改为可变绑定而不是不可变绑定:)
我不知道如何通过仅添加一个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
Run Code Online (Sandbox Code Playgroud)
编译器说明了一切:您必须替换为vec,mut vec因为默认情况下 Rust 变量是不可变的。
| 归档时间: |
|
| 查看次数: |
1425 次 |
| 最近记录: |