[Rust] Cloning the value
Following code has borrow problem:
#[test]
fn main() {
let vec0 = vec![22, 44, 66];
let vec1 = fill_vec(vec0);
assert_eq!(vec0, vec![22, 44, 66]);
assert_eq!(vec1, vec![22, 44, 66, 88]);
}
fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
let mut vec = vec;
vec.push(88);
vec
}
⚠️ Compiling of exercises/move_semantics/move_semantics2.rs failed! Please try again. Here's the output:
error[E0382]: borrow of moved value: `vec0`
--> exercises/move_semantics/move_semantics2.rs:16:5
|
12 | let vec0 = vec![22, 44, 66];
| ---- move occurs because `vec0` has type `Vec<i32>`, which does not implement the `Copy` trait
13 |
14 | let vec1 = fill_vec(vec0);
| ---- value moved here
15 |
16 | assert_eq!(vec0, vec![22, 44, 66]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `fill_vec` to borrow instead if owning the value isn't necessary
--> exercises/move_semantics/move_semantics2.rs:20:18
|
20 | fn fill_vec(vec: Vec<i32>) -> Vec<i32> {
| -------- ^^^^^^^^ this parameter takes ownership of the value
| |
| in this function
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
14 | let vec1 = fill_vec(vec0.clone());
| ++++++++
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
Follow the suggestion, we can use clone()
:
let vec1 = fill_vec(vec0.clone());
分类:
Rust
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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