rust语言match模式匹配涉及转移所有权Error Case

rust 复制代码
struct S{
    data:String,
}

//注意:因为String默认是移动语义,从而决定结构体S也是移动语义,可采用(1)或(2)两种方法解决编译错误;关键思路:放弃获取结构体S的字段data的所有权,改为借用。

fn process(s_ref:&S){//&S ,借用
    
    match *s_ref { //S , 值
    //(1) match s_ref { //&S , 借用

        //(2) S{ref data} => { //data:&String , 借用
        S{data} => { //出错点.
            
            println!("Data: {}",data);
        },
       // _ => {},
    }
}

fn main(){
    let s = S{
        data:String::from("hello world"),
    };
    
    process(&s);
}

编译错误:

rust 复制代码
   Compiling playground v0.0.1 (/playground)
error[E0507]: cannot move out of `s_ref.data` which is behind a shared reference
  --> src/main.rs:7:11
   |
7  |     match *s_ref { 
   |           ^^^^^^
...
11 |         S{data} => {
   |           ----
   |           |
   |           data moved here
   |           move occurs because `data` has type `String`, which does not implement the `Copy` trait
   |
help: consider removing the dereference here
   |
7  -     match *s_ref { 
7  +     match s_ref { 
   |

For more information about this error, try `rustc --explain E0507`.
error: could not compile `playground` (bin "playground") due to 1 previous error

注意:个人水平有限,难免谬误,欢迎指正,仅做参考,抛砖引玉;怕日后遗忘,故随笔记录。

相关推荐
the_fat_bird12 小时前
ubuntu install nvidia gpu driver
linux·运维·ubuntu
shjita12 小时前
记录java执行中的一个错误细节
java·开发语言
AI进化营-智能译站12 小时前
ROS2 C++开发系列14-Lambda表达式处理传感器数据流|文件IO保存机器人实验日志
开发语言·c++·ai·机器人
itzixiao12 小时前
L1-067 洛希极限(10分)[java][python]
java·开发语言·算法
IMPYLH12 小时前
Linux 的 tac 命令
linux·运维·服务器·bash
计算机安禾12 小时前
【Linux从入门到精通】第50篇:专栏总结与Linux学习之路的未来展望
linux·运维·学习
zhouwy11312 小时前
Linux 内核学习笔记:从零搭建内核开发与调试环境
linux
l1t12 小时前
DeepSeek总结的DuckDB anofox-forecast季节调整时间序列预测插件功能
开发语言·数据库
xyq202412 小时前
SVG 阴影
开发语言
好奇龙猫12 小时前
[大学院ーpython-base learning3: python and recommendation system ]
开发语言·python