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

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

相关推荐
你不是我我17 分钟前
【Java 开发日记】HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·开发语言·微服务
milo.qu38 分钟前
RockyLinux9.7 docker部署Jisti Meet
linux·docker·容器
GanGanGanGan_42 分钟前
CentOS 7.9 glibc 2.17 源码编译升级到 glibc 2.31
linux·运维·centos·glibc
tjl521314_211 小时前
04C++ 名称空间(Namespace)
开发语言·c++
charlie1145141911 小时前
嵌入式Linux驱动开发——class 和 device 模型 - 自动创建设备节点的幕后机制
linux·运维·驱动开发
赏金术士1 小时前
Kotlin 数据流与单双向绑定
android·开发语言·kotlin
逻辑驱动的ken2 小时前
Java高频面试场景题25
java·开发语言·深度学习·面试·职场和发展
枳实-叶3 小时前
【Linux驱动开发】第四天:dmesg日志全解+驱动加载失败极速排查
linux·运维·驱动开发
AI人工智能+电脑小能手3 小时前
【大白话说Java面试题】【Java基础篇】第32题:Java的异常处理机制是什么
java·开发语言·后端·面试
wdfk_prog3 小时前
正常关闭虚拟机时,不要点“关机”,而要点“关闭客户机”
linux·c语言·网络·ide·vscode