How to require a nested struct to implemet Deserialize trait?

⚓ rust    📅 2025-06-06    👤 surdeus    👁️ 4      

surdeus

I have a struct that contains a nested generic struct and looks like this:

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct Command<P> where P: Serialize {
    command: String,
    params: P,
}

impl<P: Serialize> Command<P> {
    pub fn new(command: &str, params: P) -> Self {
        Self {
            command: command.to_owned(),
            params
        }
    }
}

The nested struct needs to implement the Serialize and Deserialize traits too. As you can see, I can require that P implements the Serialize trait without problem, but I'm struggeling to add a similar requirement for the Deserialize trait :sweat_smile:


As soon as I add:

pub struct Command<P> where P: Serialize + Deserialize {

I get this error:

expected named lifetime parameter
help: consider making the bound lifetime-generic with a new `'a` lifetime

But this won't work either:

pub struct Command<'a, P> where P: Serialize + Deserialize<'a> {

...because of:

error[E0283]: type annotations needed: cannot satisfy `P: Deserialize<'_>`

Also, why does my "outer" struct suddenly need a life-time parameter when it didn't before?

Actually I don't want the "outer" struct to have that additional life-time parameter, if possible...

Any ideas?

Thank you and best regatrds.

7 posts - 3 participants

Read full topic

🏷️ rust_feed