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

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

相关推荐
web守墓人1 小时前
【linux】Mubuntu v1.0.11更新日志
linux·前端
好家伙VCC1 小时前
**发散创新:用Rust实现基于RAFT共识算法的轻量级分布式日志系统**在分布式系统中,**一致性协议**是保障数据可靠
java·分布式·python·rust·共识算法
哈__2 小时前
Linux生产环境MongoDB部署与安全加固:用户权限、防火墙、远程访问完整方案
linux·安全·mongodb
晔子yy2 小时前
【JAVA探索之路】从头开始讲透、实现单例模式
java·开发语言·单例模式
阿正的梦工坊7 小时前
JavaScript 微任务与宏任务完全指南
开发语言·javascript·ecmascript
知行合一。。。8 小时前
Python--05--面向对象(属性,方法)
android·开发语言·python
青梅橘子皮8 小时前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
浅时光_c8 小时前
3 shell脚本编程
linux·开发语言·bash
Evand J9 小时前
【三维轨迹目标定位,CKF+RTS,MATLAB程序】基于CKF与RTS平滑的三维非线性目标跟踪(距离+方位角+俯仰角)
开发语言·matlab·目标跟踪
Lucis__9 小时前
一文读懂TCP通信机制:基于相关API构建可靠性连接
linux·网络·tcp/ip