Serializing an euclid::Vec3D with serde

I want to serialize an euclid::Vec3D object into a json string using serde. I have this code:

use euclid::{Vector3D, UnknownUnit};
use serde::{Serialize, Deserialize};
use serde_json;

fn main() {
	let v: Vector3D<f64,UnknownUnit> = Vector3D::new(0.,1.,5.);
	let json_str = serde_json::to_string(&v).expect("Failed to serialize");
	dbg!(json_str);
}

which gives me

error[E0277]: the trait bound `Vector3D<f64, UnknownUnit>: Serialize` is not satisfied
    --> src/main.rs:7:39
     |
7    |     let json_str = serde_json::to_string(&v).expect("Failed to serialize");
     |                    --------------------- ^^ the trait `Serialize` is not implemented for `Vector3D<f64, UnknownUnit>`
     |                    |
     |                    required by a bound introduced by this call
     |
     = help: the following other types implement trait `Serialize`:
               bool
               char
               isize
               i8
               i16
               i32
               i64
               i128
             and 130 others
note: required by a bound in `serde_json::to_string`
    --> /home/me/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde_json-1.0.116/src/ser.rs:2209:17
     |
2207 | pub fn to_string<T>(value: &T) -> Result<String>
     |        --------- required by a bound in this function
2208 | where
2209 |     T: ?Sized + Serialize,
     |                 ^^^^^^^^^ required by this bound in `to_string.

I understand that the meaning of this is that the serialization method for the euclid::Vec3D objects is not implemented. From what I see, it may be possible to fix this modifying the source code of euclid by adding #[derive(Serialize, Deserialize)] just above the definition of euclid::Vec3D, however I want to keep using the standard version of euclid. How should this be done in my own codebase? My apologies if this is somehow obvious, I am relatively new to Rust.

Source – you want to enable the "serde" feature (and consider reading the documentation…)

1 Like

And if euclid didn't have a serde feature, what you'd do is instruct serde to (de)serialize your field differently, using #[serde(with = ...)].

2 Likes

Thanks! For quick reference if someone else ends up here, this is done like this in the cargo.toml file:

[dependencies]
euclid = {version = "0.22", features = ["serde"]}

And Cargo can do it for you:

cargo add euclid --features serde 
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.