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

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

相关推荐
xiaoye-duck7 分钟前
《C++ 项目:手写大模型接入 SDK》Provider分析与实现
开发语言·c++·语言模型
东城居士10 分钟前
理解Linux LCD驱动编程
linux·嵌入式系统·1024程序员节
星恒随风15 分钟前
Linux线程同步与互斥:彻底理解读者写者问题、读写锁原理、读者优先与写者优先(附pthread完整实验)
linux·服务器·笔记·1024程序员节
_upupup18 分钟前
Linux中的进程
linux·服务器·1024程序员节
denlaku27 分钟前
JDK 22 新特性详解
java·开发语言
虚无的纽扣39 分钟前
【Linux】线程同步:条件不满足时,线程该怎么等
linux·服务器·1024程序员节
爱好曙光1 小时前
生产延迟尖刺排查:用 bpftrace 抓系统调用与调度延迟
linux·ebpf·延迟·性能排查·bpftrace
“AI国潮设计-小江”1 小时前
AIGC实战:Python+SDXL批量生成英歌舞IP立牌,解锁猪猪蛋糕“反差萌”流量密码(附完整API源码)
开发语言·人工智能·python·prompt·aigc
hsg771 小时前
简述:基于Ubuntu24编译发布rust开发的html+web后端服务的方法
rust·1024程序员节
Ruiery1 小时前
Linux 6.6内核并发与同步(一):原子操作与内存屏障 — 内核同步的硬件底座
linux·运维·服务器·1024程序员节