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

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

相关推荐
TEC_INO3 分钟前
Linux58:rockx_vi_handle_thread线程的讲解
linux·运维·服务器
小此方1 小时前
Re:Linux系统篇(十三)特别篇: 实现Linux第⼀个系统程序−进度条
linux·运维·服务器
JAVA学习通2 小时前
北京明光云振铎数据科技Java面经
java·开发语言·科技
jerryinwuhan8 小时前
基于各城市站点流量的复合功能比较
开发语言·php
迈巴赫车主9 小时前
Java基础:list、set、map一遍过
java·开发语言
夏日听雨眠9 小时前
LInux(逻辑地址与物理地址的区别,文件描述符,lseek函数)
linux·运维·网络
南 阳10 小时前
Python从入门到精通day66
开发语言·python
qq_5425154111 小时前
Ubuntu 22.04.4 LTS安装ToDesk最新版打不开,无响应?旧版本4.7.2_277版本分享
linux·ubuntu·todesk
红尘散仙11 小时前
一套 Rust 核心,跑通 Tauri + React Native
react native·react.js·rust
火车叼位11 小时前
替代 Tiny Win10 的 Linux 方案:Debian XFCE 精简桌面搭建
linux·运维