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

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

相关推荐
luckyPian5 分钟前
ES6+新特性:ES7(二)
开发语言·javascript·ecmascript
稚辉君.MCA_P8_Java10 分钟前
Bash 括号:()、{}、[]、$()、$(() )、${}、[[]] 到底有什么区别?
开发语言·jvm·后端·容器·bash
Code-X011 分钟前
Bash 与 Source:命令执行的核心差异解析
开发语言·bash·1024程序员节
sinat_2869451923 分钟前
Java事故排查
java·开发语言
强里秋千墙外道31 分钟前
【Linux】ssh升级到最新版本-以ubuntu为例
linux·运维·ssh
海洋的渔夫40 分钟前
9-ruby 运算符的详解
开发语言·ruby
凯子坚持 c1 小时前
Docker LXC深度解析:从基础概念到实战演练
java·开发语言
m0_748233641 小时前
jank实现C++无缝互操作的技术探索
开发语言·c++
9ilk1 小时前
【仿RabbitMQ的发布订阅式消息队列】--- 介绍
linux·笔记·分布式·后端·rabbitmq
污斑兔1 小时前
技术随笔:Node.js ESM 中巧用 `-r dotenv/config` 解决环境变量异步加载问题
开发语言·r语言·node.js