有没有办法在不编辑实际库的源代码的情况下对库中的结构或枚举使用 #[derive] ? [英] 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?

查看:31
本文介绍了有没有办法在不编辑实际库的源代码的情况下对库中的结构或枚举使用 #[derive] ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 serde-json 的 Rust 程序,我非常喜欢它提供用于自定义结构和枚举的 #[derive(Serialize, Deserialize)] 宏.宏适用于我自己的类型.但是,我希望能够从我正在使用的其他库中调用类型上的宏.

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.

我会自己在这些类型上实现 SerializeDeserialize 特征,但是 Deserialize 的代码特别复杂,它会是为我在结构中使用的每个库类型编写代码都很痛苦.

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.

推荐答案

有没有办法在不编辑实际库的源代码的情况下对库中的结构或枚举使用 #[derive]?

不,没有.

另见:

对于 Serde 的具体情况,您可以使用 "remote deriving",但是您有提供类型的重复定义,实质上是重写原始结构.

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.

许多 crate 提供了一个特性标志来启用可选功能,所以你可能想看看你的 crate 是否有一个用于 Serde 的.如果没有,您可以将其提交给图书馆.

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.

这篇关于有没有办法在不编辑实际库的源代码的情况下对库中的结构或枚举使用 #[derive] ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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