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

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

相关推荐
Marst Code10 分钟前
Python 3.9 已停止维护!从 3.9 到 3.14 全版本深度对比,生产环境该选哪个?
开发语言·python
七牛云行业应用22 分钟前
Ollama 本地部署 DeepSeek 完全指南:macOS / Windows / Linux 三端安装 + GPU 配置 + API 调用
linux·windows·macos
ZJH__GO27 分钟前
网络编程v2--多客户端互通
java·运维·服务器·开发语言·计算机网络
万岳科技系统开发1 小时前
智慧医院小程序开发推动医疗服务流程全面线上化
大数据·开发语言·人工智能
一只小灿灿1 小时前
C++ 修饰符全面详解
开发语言·c++
马里马里奥-1 小时前
从零搭建AI Agent工具链的技术文章大纲
开发语言·qt
三言老师1 小时前
CentOS7.9:Redis服务器部署结构化实战教程
linux·运维·服务器·数据库
味悲2 小时前
Linux提权
linux·服务器·安全
不做Java程序猿好多年2 小时前
Java中 String、StringBuffer、StringBuilder 的区别详解
开发语言·python
无足鸟ICT2 小时前
【RHCA+】替换变量
linux