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

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

相关推荐
Sayai3 分钟前
Java 进程 Unable to create new native thread 排查实战:Linux 线程数五层限制与 JVM -Xss 调优
java·linux·运维·jvm·性能优化
CS_Zero6 分钟前
解决模型开发板ping不通模型终端设备问题
linux·网络
wuminyu8 分钟前
Continuation::freeze与thaw的x86_64汇编Stack Chunk拆解源码分析
java·linux·c语言·汇编·jvm·c++
事圆则缓15 分钟前
Kotlin学习导航:从知识树走到项目与面试
android·开发语言·kotlin
kunicoding18 分钟前
C++ 策略模式实战:写一个可以“一键换输出“的日志系统
开发语言·c++·策略模式
纪念 22924 分钟前
C++算法(三)
开发语言·c++·算法
程序员-Benothing24 分钟前
Linux网络排错命令:ping、traceroute、mtr、dig、nslookup
linux·运维·网络
csdn_zhangchunfeng29 分钟前
linux 如何安装rst2man命令
开发语言·chrome·python
sejinan38 分钟前
新版!IPTV直播源列表 V1.7 正式发布:接口大厅与会员定制生态解读
开发语言·php
我喜欢就喜欢42 分钟前
DeepSeek Harness 开源贡献手记:从零到合入主线的完整历程
开发语言·人工智能·copilot