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

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

相关推荐
NPE~3 分钟前
.sock 文件入门:从“文件路标”到进程间通信
linux·macos·教程·基础知识·.sock
做嵌入式网络的老骆5 分钟前
01|VSS 400MB 就是内存泄漏吗?搞懂 Linux VSS、RSS、PSS 进程内存
linux
zbguolei25 分钟前
第002篇 · 战火中的电子黎明
开发语言·php
cpolar技术支持26 分钟前
rsync -a 漏同步,-c 被 --update 吃掉
linux·备份·rsync·cpolar·数据校验
sean_wang1232 分钟前
Rust 轻量级虚拟机 smolvm 实战:200ms 冷启动、OCI 镜像直跑、单文件打包
开发语言·后端·rust·大鲸华章
战6171 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
女神下凡2 小时前
芯易选(152):炬芯(Actions)_开发指南
linux·arm开发·stm32·单片机·嵌入式硬件
郝学胜-神的一滴2 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy
zbguolei2 小时前
第001篇 · 算盘与差分机
开发语言·php