Derive serde::Serialize when struct has array as one of it's member

As you can see from the below code that I want to derive Serialize for struct Foo. But since member k is of array type this code gives me error. How do I solve this?

use serde::{Deserialize, Serialize};

#[derive(Serialize, Debug)]
struct Bar {}

#[derive(Serialize, Debug)]
struct Foo {
    k: [Bar; 100],

error :
error[E0277]: the trait bound `[Bar; 100]: Serialize` is not satisfied
    --> src/
57   |     k: [Bar; 100],
     |     ^ the trait `Serialize` is not implemented for `[Bar; 100]`
     = help: the following implementations were found:
               <[T; 0] as Serialize>
               <[T; 10] as Serialize>
               <[T; 11] as Serialize>
               <[T; 12] as Serialize>
             and 30 others

You can:

  • just use a Vec instead
  • create a newtype wrapper around [Bar; 100] and manually implement Serialize for it by forwarding to the Serialize impl on slices.

if possible could you please give me a code example for the second solution

Something along the lines of (untested):

struct SerializableArray([Bar; 100]);

impl Serialize for SerializableArray {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1 Like

Serde keeps compatibility with old versions of Rust that couldn't deal with arrays of arbitrary size (AKA const generics), so Serde can't either.

There's a workaround crate for this:

Is this really a case of low MSRV? I thought that serde and rand don't support generic arrays because they special-cased 0-sized arrays, and thus can't support const generics without either specialization or breaking backwards compatibility.

Ahh, so it's MSRV compatibility issue with a yet-unreleased version of Rust with specialization :slight_smile:

1 Like

Thanks! I think serde-big-array is easiest solution for this

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.