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

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.dtcms.com/a/61302.html

相关文章:

  • Java本地方法根据线上地址下载图片到本地然后返回本地可以访问的地址
  • 【氮化镓】开态GaN HEMTs中氧诱导Vth漂移的缺陷演化
  • 力扣:找到一个数字的 K 美丽值(C++)
  • 面试题之强缓存协商缓存
  • javascript-es6 (六)
  • 从机器学习到生成式AI狂潮:AWS的AI征程从未停息
  • 【实战ES】实战 Elasticsearch:快速上手与深度实践-7.2.2自动扩缩容策略(基于HPA)
  • 2025年总结zabbix手动部署过程!
  • 【Python爬虫】使用python脚本拉取网页指定小说章节
  • [250310] Mistral 发布世界领先的文档理解 API:Mistral OCR | 谷歌利用 AI 保护自然的三种新方式
  • 可视化图解算法:反转链表
  • 《面向长尾分布的甲骨文识别算法设计与实现 》开题报告
  • 力扣hot100二刷——哈希、双指针、滑动窗口
  • C/C++中使用CopyFile、CopyFileEx原理、用法、区别及分别在哪些场景使用
  • 【gcc编译以及Makefile与GDB调试】
  • python LLM工具包
  • JavaScript数据类型和内存空间
  • 20-智慧社区物业管理平台
  • Java【多线程】(3)单例模式与线程安全
  • 大模型如何从开始到编译出Engine
  • [免费]微信小程序(图书馆)自习室座位预约管理系统(SpringBoot后端+Vue管理端)(高级版)【论文+源码+SQL脚本】
  • 一个简化版的进程内通信库实现
  • 深入理解Java中的static关键字及其内存原理
  • 《云原生技术:DeepSeek分布式推理的效能倍增器》
  • Git系列之git checkout
  • 发起请求的步骤
  • Spring Boot整合WebSocket
  • 基于深度学习的中文文本情感分析系统
  • EasyTwin全新体验 | 春启新章,智焕新生
  • 隧道定向号角喇叭为隧道安全保驾护航