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

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

问题描述

我想序列化功能添加到我的锈结构之一。
它是一个日历事件,看起来是这样的:

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/uuid 的DateTime 来自的 https://github.com/lifthrasiir/rust-chrono

如果我尝试建立编译器抱怨连接code 未找到 UUID 项目和的DateTime ,这是因为它们都没有获得可编码德$ C $电缆,从连载箱。

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.

所以,问题是:
有没有一种方法来添加提炼出来的第三方结构不碰库本身的code?如果没有,是什么在这样的情况下添加序列化功能的最佳方式?

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?

推荐答案

首先,你不希望使用可编码可解;要使用 RustcEncodable RustcDecodable 从的 rustc序列化 箱。

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. 手动实现的特点。有时,导出不起作用,所以你必须手工编写的特质实施。在这种情况下,它会给你只是手动实现编码/解码,直接为不支持的类型的机会。

  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.

裹不支持的类型这意味着做这样的事情结构UuidWrap(酒馆UUID); 。这给你一个新的类型的的写的,这意味着你可以......嗯,做#1,但做它code量较小。当然,的现在的你必须包装和解开的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.

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

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