gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:35:52 25 4
gpt4 key购买 nike

我正在做 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/

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