serde(Serialize) vs impl deref

Hi. I'm starting with rust and instead of playing with toy programs I decided to wrap some of existing rust crates into elixir packages. It's quite easy to do it using rustler package and I have motivation to do this.
I'm trying to use serde_rustler which allows to interchange data with elixir.
The problem I facing is that the structs belong to a crate (fitparser). I got around this by creating my own structs but I wan't to use the newtype pattern.
I updated my code and now the data I'm getting back is wrapped in a tuple with the code as in the branch. It all works and sends me the data.
This is how newtype pattern works - it wraps it in a tuple. Instead of using #[derive(Serialize)] I wanted only use impl Deref to get it as before with my own structs. My intuition is that deref will also allow me to use the Serialize trait but now as soon as I remove the line (21) #[derive(Serialize)] I'm getting error on the next line (22) #[serde(rename = "Elixir.Fitparser.FitDataFieldOriginal")]
cannot find attribute serdein this scopeserde is in scope, but it is a crate, not an attribute. I tried to add use serde; but then I'm getting into a spiral of errors serde is imported here, but it is a crate, not an attribute

You can't do this.

I'm not sure what languages you're familiar with, but attributes in Rust are not metadata attached to the types that is then used elsewhere. There is no concept of "inheriting attributes". Deref has no bearing on this whatsoever, and it wouldn't make any sense for it to do so (consider that you could deref to a single field of a struct: would you expect the entire struct to suddenly support serialization?).

In order for something to be serializable with serde, there needs to be an implementation of serde::Serialize for that type specifically.

The #[serde(..)] attribute (among others) causes an error because it only has any meaning when used with the serde derivation macros. Without that, it's just gobbledygook that the compiler doesn't understand.

If you're trying to implement or customise serde for another crate's types then, I'm sorry, but you have to use newtypes. That, or customise the serialization code for every enum or struct that uses the type, which is also awful.

Thanks for your input, I updated it back to have the struct I need implemented in my code instead of newtype. I needed Deref because of a single field that is an enum with over 130 possible values and I just used deref for this single field.

1 Like