首页 > 其他分享 >[Rust] Cloning the value

[Rust] Cloning the value

时间:2024-02-27 15:46:15浏览次数:27  
标签:move value let Cloning vec0 fill Rust vec

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());

 

标签:move,value,let,Cloning,vec0,fill,Rust,vec
From: https://www.cnblogs.com/Answer1215/p/18036984

相关文章

  • [Rust] Specifying a function argument can be mutated
    Followingcodehascompileerror:#[test]fnmain(){letvec0=vec![22,44,66];letmutvec1=fill_vec(vec0);assert_eq!(vec1,vec![22,44,66,88]);}fnfill_vec(vec:Vec<i32>)->Vec<i32>{vec.push(88);vec}......
  • [Rust] Write macro
    Defineamacroanduseit:macro_rules!my_macro{()=>{println!("Checkoutmymacro!");};}fnmain(){my_macro!();} Noticethatyouhavetimedefine macrobeforemainfunction.Otherwiseitdoesn'twork. E......
  • Rust 无畏并发
    本文在原文基础上有删减,原文链接无畏并发。目录使用线程同时运行代码使用spawn创建新线程使用join等待所有线程结束将move闭包与线程一同使用使用消息传递在线程间传送数据信道与所有权转移发送多个值并观察接收者的等待通过克隆发送者来创建多个生产者共享状态并发互斥器......
  • [Rust] module with public and private methods
    Methods:modsausage_factory{//privatemethodfnget_secret_recipe()->String{String::from("Ginger")}//publicmethodpubfnmake_sausage(){get_secret_recipe();println!("sausage!&qu......
  • Rust开发日记
    Gettingstarted-RustProgrammingLanguage(rust-lang.org)  安装好配置环境变量Path:%CARGO_HOME%和%RUSTUP_HOME% 建立config文件,不要扩展名。[source.crates-io]registry="https://github.com/rust-lang/crates.io-index"#替换成你偏好的镜像源replace-......
  • 《安富莱嵌入式周报》第333期:F35战斗机软件使用编程语言占比,开源10V基准电源,不断电运
    周报汇总地址:http://www.armbbs.cn/forum.php?mod=forumdisplay&fid=12&filter=typeid&typeid=104 视频版:https://www.bilibili.com/video/BV1y1421f7ip目录:1、F35战斗机软件使用编程语言占比2、开源10V基准电源,不断电运行一年,误差小于1uV3、资讯(1)苹果开源配置语言Pkl......
  • 基于Rust的Tile-Based游戏开发杂记(01)导入
    什么是Tile-Based游戏?Tile-based游戏是一种使用tile(译为:瓦片,瓷砖)作为基本构建单位来设计游戏关卡、地图或其他视觉元素的游戏类型。在这样的游戏中,游戏世界的背景、地形、环境等都是由一系列预先定义好的小图片(即tiles)拼接而成的网格状结构。每个tile通常代表一个固定的尺寸区域,......
  • A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in
    MySQL::MySQL8.0ReferenceManual::13.2.2TheDATE,DATETIME,andTIMESTAMPTypeshttps://dev.mysql.com/doc/refman/8.0/en/datetime.html13.2.2 TheDATE,DATETIME,andTIMESTAMPTypesThe DATE, DATETIME,and TIMESTAMP typesarerelated.Thisse......
  • pandas | value_counts()的用法
    value_counts()方法返回一个序列Series,该序列用于统计某列中各个值的出现次数的函数。当配合参数bins使用时,它可以将数据分成指定的区间,然后统计每个区间内值的出现次数。value_counts()是Series拥有的方法,一般在DataFrame中使用时,需要指定对哪一列或行使用。value_counts()只......
  • [Rust] impl TryFrom and try_into()
    TheTryFromandtry_into()methodsarepartofthe.standardlibaray'sconversiontraits,designedtohandleconversionsbetweentypesinafalliblemanner-thatis,conversionsthatmightfail.Thisisincontrastto`From`and`into()`methods,wh......