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

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

相关推荐
灰灰勇闯IT1 分钟前
pto-isa:昇腾 Graph Compiler 的虚拟指令集
linux·运维·服务器
水木流年追梦5 分钟前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
.千余5 分钟前
【Linux】Socket编程UDP
linux·运维·服务器·开发语言·网络协议·学习·udp
枕星而眠7 分钟前
C++ String类精讲:从基础用法到进阶底层原理
开发语言·c++·后端·学习方法
江屿风8 分钟前
【C++笔记】模板初阶流食般投喂
开发语言·c++·笔记
Shadow(⊙o⊙)9 分钟前
qt信号和槽链接的接入与断开
开发语言·前端·c++·qt·学习
AI玫瑰助手11 分钟前
Python运算符:逻辑运算符(and/or/not)的短路特性
开发语言·python·信息可视化
m0_4746067812 分钟前
JAVA - 使用Apache POI 自定义报表字段手写导出(支持-合并单元格)
java·开发语言·apache
肩上风骋12 分钟前
C++基本知识点积累之d指针,invokemethod函数(一)
开发语言·c++·d指针·invokemethod()
明志数科13 分钟前
具身智能数据标注工具对比评测:6大平台横向测评
开发语言·python