Serde serialize_with attribute


#1

Hello, I would like to use serialize_with attribute.
Unfortunately, examples that I found on the web doesn’t compile.

I found the similar question on SO https://stackoverflow.com/questions/39383809/how-to-transform-fields-during-serialization-using-serde
I updated it a little bit according to compiler, however, one error is still present.

extern crate serde;
#[macro_use]
extern crate serde_derive;
use serde::Serializer;

fn round_serialize<S>(x: &f32, s: &mut S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_f32(x.round())
}

#[derive(Debug, Serialize)]
pub struct NodeLocation {
    #[serde(rename = "nodeId")]
    id: u32,
    #[serde(serialize_with = "round_serialize")]
    lat: f32,
    #[serde(serialize_with = "round_serialize")]
    lon: f32,
}

fn main() {

}
error[E0308]: mismatched types
  --> examples/ser_with.rs:13:17
   |
13 | #[derive(Debug, Serialize)]
   |                 ^^^^^^^^^
   |                 |
   |                 expected &mut _, found type parameter
   |                 help: consider mutably borrowing here: `&mut Serialize`
   |
   = note: expected type `&mut _`
              found type `__S`

error: aborting due to previous error

This implementation is done according to docs.
Looks like an errors occurs somewhere inside a macro and I not sure what is the problem and how to fix it.

Could you please help to figure it out?


#2

Not quite - you need:

fn round_serialize<S>(x: &f32, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.serialize_f32(x.round())
}

Note that s is just S, not &mut S.


#3

Oh my.
I am totally blind.
Thank you very much @vitalyd !