Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

serialization - Add Serialize attribute to type from third-party 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>,
}

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. 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.

  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...