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

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

相关推荐
weixin199701080164 分钟前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
尘客-追梦12 分钟前
Day 01:插件化之前,先看清 ABI 这堵墙
开发语言·c++·qt
持敬chijing41 分钟前
Python-数据类型-列表
开发语言·python·青少年编程
两点王爷1 小时前
解决 Linux 中 version `CXXABI_1.3.8‘ not found 报错
linux·运维·服务器
xx~t1 小时前
嵌入式——51单片机1
linux·c语言·单片机·嵌入式硬件·51单片机
啦啦啦啦啦zzzz1 小时前
利用RAII机制进行日志的采集
linux·服务器·c++·网络编程·c++20
0+1111 小时前
Linux --线程概念与控制
linux·运维·服务器·jvm
nLif2 小时前
基于GTK的简易MFC对话框兼容层 -- MfcToGTK
linux·c++·mfc·gtk
写后端的胖头鱼2 小时前
【高频面试题】Java 基础类型 + 包装类 + String 互相转换
java·开发语言
matlab代码2 小时前
基于matlab自助水果超市水果识别收费系统(GUI界面)【源码67期】
开发语言·matlab