[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 @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-27 [Typescript] The partial Inference Problem
2019-02-27 [Functional Programming] Use Task/Async for Asynchronous Actions
2019-02-27 [Functional Programming] Working with two functors(Applicative Functors)-- Part2 --liftAN
2018-02-27 [CSS3] Create Dynamic Styles with CSS Variables
2017-02-27 [Flow] The Fundamentals of Flow
2017-02-27 [Angular] Some performance tips
2017-02-27 [Ramda] Rewrite if..else with Ramda ifElse
点击右上角即可分享
微信分享提示