rust - 如何解决 RuSTLings 练习 "move_semantics3.rs"?

标签 rust

我正在做 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 had let mut vec = vec; is no longer there. You can, instead of adding that line back, add mut 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/

相关文章:

rust - 如何在处理程序之间传递变量

lifetime - 嵌套生命周期

input - 如何在 Rust 中读取用户输入?

rust - 特性未实现(实现特性的事物)

rust - 如何使用生命周期边界来解决 "reference must be valid for the static lifetime"

rust - 如何在不需要显式值的情况下使一个论点暗示另一个论点? (--foo,不是--foo true)

rust - 将 `Deref` 实现为返回复合结构的字段是惯用的吗?

rust - 如何使用macro_rules 定义带有可选#[cfg] 的结构?

rust - 何时使用 Rc 与 Box?

rust - 迭代特征对象的可变引用向量