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

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

相关推荐
Ronin3052 分钟前
【Linux网络】Socket编程:UDP网络编程实现ChatServer
linux·网络·udp
面向对象World38 分钟前
正点原子Mini Linux 4.3寸800x480触摸屏gt115x驱动
linux·服务器·数据库
jz_ddk44 分钟前
[指南] Python循环语句完全指南
开发语言·python·continue·循环·for·while·break
chilavert3181 小时前
技术演进中的开发沉思-368:锁机制(中)
java·开发语言·jvm
17(无规则自律)1 小时前
LubanCat 2烧录一个新镜像后开发环境搭建
linux·嵌入式硬件·考研·软件工程
大黄说说1 小时前
MySQL数据库运维管理基础知识:从安装到日常维护的完整指南
开发语言
HAPPY酷1 小时前
C++ 多线程实战三板斧
java·开发语言·c++·技术美术
独自破碎E1 小时前
BISHI54货物堆放
android·java·开发语言
『往事』&白驹过隙;2 小时前
浅谈PC开发中的设计模式搬迁到ARM开发
linux·c语言·arm开发·设计模式·iot
顾北122 小时前
SpringCloud 系列 04:Gateway 断言 / 过滤器 / 限流 一站式落地指南
java·开发语言·数据库