8

I am working on a Rust program that uses serde-json, and I really like the #[derive(Serialize, Deserialize)] macros that it gives for use with custom structs and enums. The macros work just fine with my own types. However, I would like to be able to call the macros on types from other libraries that I am using.

I would implement the Serialize and Deserialize traits on those types myself, but the code for Deserialize is especially convoluted, and it would be a pain to write to for every single library type that I use in a struct.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kai Schmidt
  • 701
  • 8
  • 14

1 Answers1

16

Is there a way for me to use #[derive] on a struct or enum from a library without editing the actual library's source code?

No, there is not.

See also:


For the specific case of Serde, you can use "remote deriving", but you have to provide a duplicate definition of the type, essentially rewriting the original structure.

Many crates provide a feature flag to enable optional functionality, so you may want to look to see if your crate has one for Serde. If it doesn't, you could submit such to the library.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • @mcarton the tricky thing is that it assumes there's One True Way to serialize a data structure. In addition, the specific serialization format is now part of the public API of the crate and can't be changed without a major version bump. I totally understand why many maintainers wouldn't want to take on that extra work. – Shepmaster Jan 15 '18 at 22:49
  • To add, a note about `serialize_with` & `deserialize_with` – Stargateur Mar 05 '20 at 23:30