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

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

相关推荐
idolao21 分钟前
CentOS 7 安装 httpd-2.4.1.tar.gz 详细步骤(源码编译、配置、启动)
linux·运维·centos
wangjialelele1 小时前
Linux mmap 机制:从 read/write 底层流程到手写 malloc 内存分配
linux·运维·服务器·mmap
RPGMZ1 小时前
RPGMZ游戏引擎 一个窗口 文本居中显示
开发语言·javascript·游戏引擎·rpgmz
草莓熊Lotso1 小时前
【Linux网络】UDP Socket 编程全解析:从回显服务到通用字典服务,从零实现工业级代码
linux·运维·服务器·数据库·c++·单片机·udp
一只积极向上的小咸鱼3 小时前
Codex 在 VS Code + ModelArts 场景下的登录与配置总结
linux·运维·windows
Waay8 小时前
Linux Shell 知识点考评(一):grep 文本搜索(附答案)
linux·运维·服务器
jamon_tan8 小时前
Linux下串口RAW模式设置
linux
碧海银沙音频科技研究院8 小时前
基于VMware虚拟机ubuntu开发博通BK7258方法
linux·运维·ubuntu
代钦塔拉9 小时前
Qt4 vs Qt5 带参数信号槽的连接方式详解
开发语言·数据库·qt
云边有个稻草人11 小时前
【Linux系统】进程地址空间
linux·虚拟地址空间·进程地址空间·虚拟地址空间是怎么实现的?·为什么要有虚拟地址空间?·怎么理解虚拟地址空间?