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

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

相关推荐
延延oO2 分钟前
zyzyzyzyzy
linux
小白不想白a7 分钟前
linux排障:服务端口被打满
linux·服务器·网络
CryptoPP9 分钟前
对接API获取马来西亚历史数据
linux·运维·服务器·金融·区块链
Cyber4K23 分钟前
【Kubernetes专项】K8s集群1.31版本安装手册
linux·docker·云原生·容器·kubernetes
lsx20240633 分钟前
Eclipse 添加书签
开发语言
易营宝41 分钟前
高效的跨境电商广告优化系统:易营宝广告投放实操指南
大数据·开发语言·人工智能·php
superman超哥44 分钟前
路由的艺术:Rust Web 框架中的高效匹配与类型安全提取
开发语言·rust·编程语言·rust web框架·rust路由
hqwest1 小时前
码上通QT实战22--趋势页面01-准备图表对象
开发语言·qt·qpainter·qss·painevent·qt绘图事件
陈让然1 小时前
WSL2 ubuntu18.04扩容
linux·运维·ubuntu
hqwest1 小时前
码上通QT实战23--趋势页面02-图表模拟数据
开发语言·qt·qpainter·qt绘图·绘制曲线