1
votes

I'm rather new to Rust, but was looking to use it for some numerics work and started exploring the ndarray crate a bit. Doing so, however, I got a bit stumped trying to derive serde::Serialize and serde::Deserialize for structs containing arrays.

In particular, I tried to compile the following snippet but got an error in doing so:

extern crate serde;
use ndarray::{ Array1 };
use serde::{ Serialize, Deserialize };

#[derive(Serialize, Deserialize)]
pub struct Canary {
    pub xs: Array1<f64>
}
error[E0277]: the trait bound `ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 1]>>: serde::Serialize` is not satisfied
  --> src/lib.rs:40:5
   |
40 |     pub xs: Array1<f64>
   |     ^^^ the trait `serde::Serialize` is not implemented for `ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 1]>>`
   |
   = note: required by `serde::ser::SerializeStruct::serialize_field`
# Cargo.toml
[dependencies]
ndarray = { version = "0.12.1", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }

Looking at the bounds on impl<A, D, S> Serialize for ArrayBase<S, D> where A: Serialize, D: Dimension + Serialize, S: Data<Elem = A>, I'm a bit confused as to what the error is, since A = f64 implements Serialize, and since D = Dim<[usize; 1]> implements both Dimension and Serialize. Is there something I'm missing in order to derive serialization for structs containing arrays? Thanks!

1
Does switching ndarray to version 0.13.1 have any effect? - Locke
@Locke: That solved it, thank you! Would you be willing to post that as an answer so that I can mark it as correct and give you the karma? - Chris Granade

1 Answers

2
votes

The latest version of ndarray is 0.13.1.

Updating the version in your Cargo.toml should fix the issue:

[dependencies]
ndarray = { version = "0.13.1", features = ["serde"] }

This answer was suggested by @Locke in a comment. I just created a small answer for future visitors.