将序列化属性添加到来自第三方库的类型 [英] Add Serialize attribute to type from third-party lib

查看:23
本文介绍了将序列化属性添加到来自第三方库的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将序列化功能添加到我的 Rust 结构之一.这是一个日历事件,如下所示:

I'm trying to add serialization functionality to one of my structs in Rust. It's an event for a calendar and looks like this:

#[derive(PartialEq, Clone, Encodable, Decodable)]
pub struct Event {
    pub id: Uuid,
    pub name: String,
    pub desc: String,
    pub location: String,
    pub start: DateTime<Local>,
    pub end: DateTime<Local>,
}

该结构使用来自第三方的两种不同类型,Uuid 来自 https://github.com/rust-lang/uuidhttps://github.com/lifthrasiir/rust-chrono.

The struct uses two different types from third-parties, the Uuid is from https://github.com/rust-lang/uuid and the DateTime from https://github.com/lifthrasiir/rust-chrono.

如果我尝试构建项目,编译器会抱怨 UuidDateTime 找不到 encode,这是因为它们都存在不从 serialize crate 派生 EncodableDecodeable.

If I try to build the project the compiler complains that encode was not found for Uuid and DateTime, which is because they both do not derive Encodable and Decodeable, from the serialize crate.

所以问题是:有没有办法在不接触库本身代码的情况下将派生添加到第三方结构?如果没有,在这种情况下添加序列化功能的最佳方法是什么?

So the questions are: Is there a way to add derives to third-party structs without touching the code of the libs itself? If not, what is the best way to add serialization functionality in a situation like this?

推荐答案

首先你不想使用EncodableDecodable;你想使用 rustc-serialize<中的 RustcEncodableRustcDecodable/code> 箱子.

First of all, you don't want to use Encodable and Decodable; you want to use RustcEncodable and RustcDecodable from the rustc-serialize crate.

其次,你不能.如果你没有写出有问题的类型有问题的特征,你就不能:这是编译器的故意保证.(另见连贯性".)

Secondly, you can't. If you didn't write the type in question or the trait in question, you just can't: this is a deliberate guarantee on the part of the compiler. (See also "coherence".)

在这种情况下你可以做两件事:

There are two things you can do in this situation:

  1. 手动实现 trait. 有时,derive 不起作用,因此您必须手动编写 trait 实现.在这种情况下,您可以直接手动为不支持的类型实现编码/解码.

  1. Implement the traits manually. Sometimes, derive doesn't work, so you have to write the trait implementation by hand. In this case, it would give you the opportunity to just manually implement encoding/decoding for the unsupported types directly.

包装不支持的类型.这意味着执行 struct UuidWrap(pub Uuid); 之类的操作.这为您提供了一种 编写的新类型,这意味着您可以...好吧,执行 #1,但代码量较少.当然,现在你必须包装和解开 UUID,这是一个的痛苦.

Wrap the unsupported types. This means doing something like struct UuidWrap(pub Uuid);. This gives you a new type that you wrote, which means you can... well, do #1, but do it for a smaller amount of code. Of course, now you have to wrap and unwrap the UUID, which is a bit of a pain.

这篇关于将序列化属性添加到来自第三方库的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆