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

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

相关推荐
dadaobusi1 分钟前
Linux内核完成大量内存/调度/时间子系统初始化的关键阶段
java·linux·前端
唐墨1231 分钟前
关于linux kernel错误码为负数编码这件事情,我个人的一些看法
linux·运维·服务器
Full Stack Developme8 分钟前
Linux Shell 教程概览
linux·前端·chrome
kyle~9 分钟前
DDS分布式实时系统---自省机制
开发语言·分布式·机器人·c#·接口·ros2
yujunl9 分钟前
Integrated Security=True(Windows 集成身份验证)
开发语言
右耳朵猫AI10 分钟前
Python周刊2026W23 | Polars 1.41、PyPy v7.3.23、Python 3.15、httpx2、dj-lite-tenant
开发语言·python
网络系统管理16 分钟前
第八届江苏技能状元大赛选拔赛信息通信网络运行管理项目模块D网络服务与系统运维-Linux样题
linux·运维
昭昭颂桉a17 分钟前
TypeScript 前端的必修课,从 JS 到 TS
开发语言·前端·javascript·typescript
何以解忧,唯有..18 分钟前
Go 语言安装与环境配置完整指南
开发语言·后端·golang
guyoung22 分钟前
BoxAgnts 工具系统(5)——WASM 工具开发:从 Hello World 到生产部署
rust·agent·ai编程