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

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

相关推荐
gz927cool几秒前
Python 全栈应用最佳实践完整指南
开发语言·python·ai
Android系统攻城狮18 分钟前
Linux FFmpeg深度解析之avcodec_parameters_from_context调用流程与实战(十六)
linux·运维·ffmpeg·音视频进阶·ffmpeg音视频·车载音视频进阶
CoderYanger18 分钟前
Java EE 进阶:5. Spring IoC&DI(第三弹):Spring DI
java·开发语言·spring boot·spring·面试·java-ee·mvc
思想觉悟22 分钟前
SEAndroid实战
android·linux·c++
AIFQuant24 分钟前
Python期货行情API接入:股指、黄金、原油多品种数据管道实战
开发语言·python·金融·区块链·量化开发
Thneonl25 分钟前
Claude Code 频繁 Compacting?发布次日我根治了 2 个痛点
后端·rust
echome88825 分钟前
JavaScript async/await 错误处理:别让 Promise 静默失败
开发语言·前端·javascript·promise
运维行者_28 分钟前
供应链安全成最大风险源,企业如何构建可控的运维体系?
运维·开发语言·网络·数据库·安全·云计算·流量监控
.YM.Z37 分钟前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
逆向编程41 分钟前
MATLAB高级数据结构:cell、struct与table深度应用
开发语言·数据结构·matlab