Skip to content
On this page

Move语义1: exercises/move_semantics/move_semantics1.rs

题目

rust
// move_semantics1.rs
//
// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand
// for a hint.

// I AM NOT DONE

fn main() {
    let vec0 = Vec::new();

    let 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> {
    let mut vec = vec;

    vec.push(22);
    vec.push(44);
    vec.push(66);

    vec
}

题目解析

编译器提示信息如下:

txt
⚠️  Compiling of exercises/move_semantics/move_semantics1.rs failed! Please try again. Here's the output:
error[E0596]: cannot borrow `vec1` as mutable, as it is not declared as mutable
  --> exercises/move_semantics/move_semantics1.rs:15:5
   |
15 |     vec1.push(88);
   |     ^^^^^^^^^^^^^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
11 |     let mut vec1 = fill_vec(vec0);
   |         +++

error: aborting due to previous error

For more information about this error, try `rustc --explain E0596`.

从错误信息能读出的信息:

  • 无法对不可变局部变量vec1进行可变借用
  • 提示我们添加在变量vec1上添加mut
rust
fn main() {
    let vec0 = Vec::new();

    let vec1 = fill_vec(vec0); 
    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);
}

这个题目中,因为在调用fill_vec(vec0)函数的时候,将vec0当作参数传入,vec0由于是Vec类型,会Move转移所有权到fill_vec函数中。所以fill_vec(vec0)结束后,vec0应该是不可用的,你可以尝试再访问一下vec0试一下。

参考资料

Powered by VitePress