[Rust] Specifying a function argument can be mutated

Following code has compile error:

#[test]
fn main() {
    let vec0 = vec![22, 44, 66];

    let mut vec1 = fill_vec(vec0);

    assert_eq!(vec1, vec![22, 44, 66, 88]);
}

fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
    vec.push(88);

    vec
}
Progress: [##########################>---------------------------------] 42/96 (43.8 %)                             
⚠️  Compiling of exercises/move_semantics/move_semantics3.rs failed! Please try again. Here's the output:
warning: variable does not need to be mutable
  --> exercises/move_semantics/move_semantics3.rs:14:9
   |
14 |     let mut vec1 = fill_vec(vec0);
   |         ----^^^^
   |         |
   |         help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

error[E0596]: cannot borrow `vec` as mutable, as it is not declared as mutable
  --> exercises/move_semantics/move_semantics3.rs:20:5
   |
20 |     vec.push(88);
   |     ^^^ cannot borrow as mutable
   |
help: consider changing this to be mutable
   |
19 | fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
   |             +++

error: aborting due to previous error; 1 warning emitted

 

Follow the suggest, mark argument as mut:

#[test]
fn main() {
    let vec0 = vec![22, 44, 66];

    let mut vec1 = fill_vec(vec0);

    assert_eq!(vec1, vec![22, 44, 66, 88]);
}

fn fill_vec(mut vec: Vec<i32>) -> Vec<i32> {
    vec.push(88);

    vec
}

 

posted @ 2024-02-27 15:37  Zhentiw  阅读(12)  评论(0)    收藏  举报