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

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

相关推荐
Niuguangshuo3 分钟前
silero-vad:超轻量级开源 VAD 实践指南
开发语言·python
深念Y28 分钟前
从 Windows 迁移到 Linux 开发环境的记录
linux·windows·链接·bun·ram·imdisk
哭哭啼31 分钟前
JAVA服务问题诊断
java·开发语言·jvm
小灰灰搞电子37 分钟前
Rust+Slint 实现温度计源码分享
前端·rust·slint
GitLqr1 小时前
2026 Bun 全新姿态:从 Zig 到 Rust 的“暴力”重构与生态大爆发
rust·node.js·bun
知无不研1 小时前
Linux I/O复用之epoll
linux·服务器·epoll·socket编程
CRMEB定制开发2 小时前
2026年最值得推荐的10大开源商城系统盘点
开发语言·人工智能·开源·商城系统·小程序商城
苏宸啊2 小时前
linux网络编程udp服务器和客户端代码编写(echo版本和字典版本)
linux·网络
buhuizhiyuci3 小时前
【QT-百日筑基篇】修真世界摸爬滚打多年,终于黄天不负有心人,突破炼器中期——常用控件QWight的属性
开发语言·c++·qt·gui·图形化
~|Bernard|3 小时前
Linux 定时任务(Cron)完整教程
linux·运维·服务器