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

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

相关推荐
xlp666hub15 小时前
Leetcode第五题:用C++解决盛最多水的容器问题
linux·c++·leetcode
张宏23616 小时前
原子操作 (基于Linux 应用层 C 语言)
linux
AI智动派16 小时前
从 Python 到 Rust:深入解析 LLM Agent 工具调用的内存安全与异步并发重构实践
rust
_朱志鹏16 小时前
Rust练手项目1--minigrep
rust
kymjs张涛1 天前
OpenClaw 学习小组:初识
android·linux·人工智能
程序设计实验室1 天前
经历分享,发现挖矿木马后,服务器快速备份与重装(腾讯云平台)
linux
Miku161 天前
OpenClaw-Linux+飞书官方Plugin安装指南
linux·人工智能·agent
Miku161 天前
OpenClaw 接入 QQ Bot 完整实践指南
linux·人工智能·agent
ssshooter2 天前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
AI智动派2 天前
《深入 Rust Async/Await:如何实现一个带超时保护与安全沙箱的 LLM Agent 循环》
rust