首页 > 其他分享 >rust结构体包含另一个结构体引用时,serde序列化问题

rust结构体包含另一个结构体引用时,serde序列化问题

时间:2024-02-20 15:58:13浏览次数:21  
标签:serde string Deserialize Person person msg 序列化 id rust

代码如下

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Person {
    id: String,
    name: String,
}

#[derive(Serialize, Deserialize)]
struct Msg<'a> {
    id: String,
    person: &'a Person,
}

fn main() {
    let person = Person {
        id: "123".to_string(),
        name: "Alice".to_string(),
    };

    let msg = Msg {
        id: "456".to_string(),
        person: &person,
    };

    let msg_str = serde_json::to_string(&msg).unwrap();
    println!("Serialized Msg: {}", msg_str);
}

报错如下

error[E0277]: the trait bound `&'a Person: Deserialize<'_>` is not satisfied
    --> src/main.rs:2463:13
     |
2463 |     person: &'a Person,
     |             ^^^^^^^^^^ the trait `Deserialize<'_>` is not implemented for `&'a Person`
     |
note: required by a bound in `next_element`
    --> /home/alxps/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.195/src/de/mod.rs:1726:12
     |
1724 |     fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
     |        ------------ required by a bound in this associated function
1725 |     where
1726 |         T: Deserialize<'de>,
     |            ^^^^^^^^^^^^^^^^ required by this bound in `SeqAccess::next_element`
help: consider removing the leading `&`-reference
     |
2463 -     person: &'a Person,
2463 +     person: Person,
     |

我不想让msg有person所有权,也不想clone person,现在要自定义序列化实现trait,person字段类型改成Cow<'a, Person>之类的就好了。代码修改如下

use std::borrow::Cow;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize)]
struct Person {
    id: String,
    name: String,
}

#[derive(Serialize, Deserialize)]
struct Msg<'a> {
    id: String,
    person: Cow<'a, Person>,
}

fn main() {
    let person = Person {
        id: "123".to_string(),
        name: "Alice".to_string(),
    };

    let msg = Msg {
        id: "456".to_string(),
        person: Cow::Borrowed(&person),
    };

    let msg_str = serde_json::to_string(&msg).unwrap();
    println!("Serialized Msg: {}", msg_str);
}

参考链接 

1、rust中文社区提问

2、稀土掘金rust Cow博客

标签:serde,string,Deserialize,Person,person,msg,序列化,id,rust
From: https://www.cnblogs.com/ALXPS/p/18023272

相关文章

  • [Rust] Integer Types in Rust
    Thislessontalksabout Integer typesinRustandthatthereare unsigned and signed integers.Italsoexplainshoweverythetypenamesarecomposedof"u"and"i",forunsignedandsignedrespectively,followedbytheir withinbits.......
  • [Rust] parse().unwrap()
    Thislessonexplains TypeInference inRustandhowitallowsthecompilertofigureoutbyitself,whattypevariableshavewhentheygettheirvaluesassigned.Therearecaseswhenthecompilercannotinferavalue'stypethroughstaticanalysis.I......
  • [Rust] Use Impl with Struct
    useanyhow::{Result,anyhow};usestd::str::FromStr;fnget_input()->&'staticstr{return"0,9->5,98,0->0,89,4->3,42,2->2,17,0->7,46,4->2,00,9->2,93,4->1,40,0->8,85,5->8,2&q......
  • 远程控制软件RustDesk自建服务器全平台部署及使用教程
    RustDesk挺出名的一款远程控制,远程协助的开源软件。完美替代TeamViewer,ToDesk,向日葵等平台。关键支持自建服务器,更安全私密远程控制电脑!其中客户端支持安卓,且支持控制安卓手机。官方地址官网:https://rustdesk.com/开源地址:https://github.com/rustdesk/一、准备工作1,有自己......
  • JAVA基础-序列化
    1,什么是序列化?Java序列化是指把Java对象转换为字节序列的过程,而Java反序列化是指把字节序列恢复为Java对象的过程。2,序列化的使用场景永久性保存对象,保存对的字节序列到本地文件或者数据库中;通过序列化以字节流的形式对象在网络中进行传递和接收;通过序列化在进程间传递......
  • 教你用Rust实现Smpp协议
    本文分享自华为云社区《华为云短信服务教你用Rust实现Smpp协议》,作者:张俭。协议概述SMPP(ShortMessagePeer-to-Peer)协议起源于90年代,最初由Aldiscon公司开发,后来由SMPP开发者论坛维护和推广。SMPP常用于在SMSC(ShortMessageServiceCenter,短信中心)和短信应用之间传输短消息......
  • 【常见问题】Java 8 date time type `java.time.LocalDateTime` not supported by def
    问题描述将一个包含LocalDateTime对象的集合进行序列化和反序列化时,可能会遇到以下异常:Causedby:com.fasterxml.jackson.databind.exc.InvalidDefinitionException:Java8date/timetype`java.time.LocalDate`notsupportedbydefault:addModule"com.fasterxml.jack......
  • jackson序列化问题
    在对对象进行jackson序列化的时候,有时候会出现序列化后的变量名称大小写错误的情况。测试的实体类TestEntity2如下:public class TestEntity2 {    private String aBcd;    private String qWER;    private String qWERty;    private String qWERty......
  • [Rust] Macros vs. Functions
    InRust,theexclamationmark(!)afteranameindicatesthatitisamacroratherthanafunction.MacrosandfunctionsinRustarecalleddifferentlyandservedifferentpurposes.Macros,likeanyhow!,candothingsthatfunctionscannot,suchasgenera......
  • [Rust] Error handling with Enum
    Wecanuse ReusltenumtodoerrorhandlingtypeResult<V,E>{Err(E),Ok(V)} Example://():empty//uszie:justreturnaintegreaserrorfordemofnerror_me(throw:bool)->Result<(),usize>{ifthrow{returnEr......