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

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

相关推荐
曹牧1 分钟前
Java:Unix时间戳
java·开发语言
linux开发之路2 分钟前
C++项目推荐:eBPF+调度器性能分析框架
linux·c++·ebpf·火焰图·调度器
会编程的土豆8 分钟前
Go 里的 error 接口 + 假 nil(超级重点)
开发语言·后端·golang
愿天垂怜8 分钟前
【C++脚手架】ffmpeg 库的介绍与使用
linux·服务器·开发语言·c++·ide·git·ffmpeg
并不喜欢吃鱼9 分钟前
从零开始 C++-----十一【C++ 数据结构】红黑树全解析:从定义到工程实现(一文搞定,十分详细)
开发语言·数据结构·c++
不会C语言的男孩11 分钟前
C++ Primer Plus 第7章:函数——C++的编程模块
开发语言·c++
方也_arkling11 分钟前
【Java-Day09】继承
java·开发语言
迈巴赫车主12 分钟前
蓝桥杯21247弹跳鞋java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
jimy112 分钟前
Linux动态加载器,loader,dynamic linker
linux·运维·服务器
kongba00715 分钟前
ttyd Web终端安装指南(OpenCloudOS 9)
linux·前端