当前位置: 首页 > article >正文

rust语言match模式匹配涉及转移所有权Error Case

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);
}

编译错误:

   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

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


http://www.kler.cn/a/581953.html

相关文章:

  • Flutter中stream学习
  • 【threejs实战教程一】初识Three.js,场景Scene、相机Camera、渲染器Renderer
  • python django orm websocket html 实现deepseek持续聊天对话页面
  • Git 的基本概念和使用方式。
  • 第4节: 静态路由与动态路由协议(RIP、OSPF)详解
  • 【算法】二叉树的递归遍历
  • 使用外挂工具,在教师资格面试抽题系统中自动填入身份证号
  • ubuntu 和 RV1126 交叉编译Mosqutiio-1.6.9
  • Jenkins在Windows上的使用(一):用户配置
  • 大数据学习(60)-HDFS文件结构
  • nginx反向代理应用
  • 【Academy】JWT 分析 ------ JWT
  • HTTP发送POST请求的两种方式
  • 全局引用scss文件定义的变量
  • JavaScript与UniApp、Vue、React的关系
  • 【RabbitMQ】事务
  • 车间图纸安全传输需要注意什么?
  • PostgreSQL - Windows PostgreSQL 卸载
  • 物联网IoT系列之MQTT协议基础知识
  • 入门到入土,Java学习 day16(算法1)