Trait `serde::ser::Serialize` is not implemented for `dyn std::fmt::Display`

I'm trying to dynamic types to the HashMap but when i try using the Box struct i get this error.

        let mut payload: HashMap<&str, Box<dyn Display + 'static>> = HashMap::new();
        payload.insert("reference", Box::new(reference));
        payload.insert("amount", Box::new(amount));
        payload.insert("customer_name", Box::new(customer_name));
        payload.insert("customer_email", Box::new(customer_email));
        payload.insert("coin", Box::new(coin));
        payload.insert("currency", Box::new(currency));
        payload.insert("api_public_key", Box::new(api_public_key.unwrap()));
        payload.insert("accept_partial_payment", Box::new(accept_partial_payment));

        let client = Client::new();
        let response =


trait serde::ser::Serialize is not implemented for dyn std::fmt::Display

I think what you meant to use is HashMap<&str, Box<dyn serde::ser::Serialize + 'static>>.

I don't think that would work. Serialize is only useful if you can call the generic serialize() method on it, which you can't on a trait object.

Thank you for your response,

I get this new error

the trait Serialize cannot be made into an object
required because of the requirements on the impl of CoerceUnsized<Box<dyn Serialize>> for Box<std::string::String>
required by cast to type Box<(dyn Serialize + 'static)>

Yes, I was wrong. This doesn't work because of the reasons @H2CO3 stated above.

A possible workaround might be to use the erased_serde crate.

1 Like