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

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

相关推荐
忘了ʷºᵇₐ3 小时前
在IDEA 2024.1版本中如何打开Remote Host及连接linux
linux·运维·服务器
零K沁雪4 小时前
Linux 内核中与网络地址相关的函数
linux·内核
0xDevNull6 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
小小亮016 小时前
Next.js基础
开发语言·前端·javascript
steins_甲乙6 小时前
# 从 0 做一个小型内存泄漏检测器:开篇与架构设计
linux
ALex_zry6 小时前
C++网络编程心跳机制与连接保活:长连接稳定性保障
开发语言·网络·c++
Amumu121387 小时前
Js:正则表达式(二)
开发语言·javascript·正则表达式
蒸蒸yyyyzwd7 小时前
后端学习笔记 day4
linux·笔记·学习
Sgf2277 小时前
ES8(ES2017)新特性完整指南
开发语言·javascript·ecmascript
upp7 小时前
[最新版本centos 10系统制作与安装]
linux·运维·centos