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?
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With