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

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

相关推荐
wengqidaifeng29 分钟前
C++从菜鸟到强手:1.基础入门
开发语言·c++
hhb_61831 分钟前
PHP 8.x 核心特性与工程化开发实践指南
开发语言·php
geovindu1 小时前
go: Flyweight Pattern
开发语言·设计模式·golang·享元模式
xyq20242 小时前
TypeScript中的String类型详解
开发语言
爱学习的小囧8 小时前
ESXi 8.0 原生支持 NVMe 固态硬盘吗?VMD 配置详解教程
linux·运维·服务器·esxi·esxi8.0
坚持就完事了8 小时前
Linux中的变量
linux·运维·服务器
小糖学代码8 小时前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
handler018 小时前
从源码到二进制:深度拆解 Linux 下 C 程序的编译与链接全流程
linux·c语言·开发语言·c++·笔记·学习
Cat_Rocky9 小时前
利用Packet Tracer网络实验
linux·运维·服务器
小白学大数据9 小时前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构