Getting data from Generic`

I am trying to achieve what exist in below code, I am trying to call get_type() function from Generic type in AuthorizationDetails Is that possible?

In the end, I just need to populate the value DataFromat and put it in format field.

use serde::{de::DeserializeOwned, Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct AuthorizationDetails<T: DataFormat> {
    pub type_: String,
    pub location: Option<Vec<String>>,
    pub format: T::DataFormat::get_type(), // How to make this one possible??
    pub credentail_definition: CredentialDefinition<T>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum CredentialDefinition<T: DataFormat> {
    JwtVcJson(T),
    JwtVcJsonLd(T),
    LdpVc(T),
    MsoMdoc(T),
}

pub trait DataFormat: Serialize {
    fn get_type(&self) -> String;
}

#[derive(Serialize, Deserialize, Debug)]
pub struct JwtVcJson {
    #[serde(rename = "type")]
    pub x_type: String,

    #[serde(rename = "credentialSubject")]
    pub credential_subject: Option<serde_json::Value>,
}

impl DataFormat for JwtVcJson {
    fn get_type(&self) -> String {
        "JwtVcJson".to_string()
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct MsoMdoc {
    pub data: String,
}

impl DataFormat for MsoMdoc {
    fn get_type(&self) -> String {
        "MsoMdoc".to_string()
    }
}

mod test {
    use super::*;

    #[test]
    fn test() {
        let auth_details = AuthorizationDetails {
            type_: "test".to_string(),
            location: None,
            credentail_definition: CredentialDefinition::JwtVcJson(JwtVcJson {
                x_type: "test".to_string(),
                credential_subject: None,
            }),
        };

        let serialized = serde_json::to_string(&auth_details).unwrap();
        println!("{}", serialized);
    }
}

Please don't share your code as a screenshot but copy and paste it into your post wrapped in three backticks:

```
<paste code here>
```

Screen-readers can't interpret screenshots and seemingly neither can I because I'm unable to understand what you are trying to achieve and what your problem is.

2 Likes

Sorry, I made the changes

Thanks, much better. I'm still not sure what you are trying to achieve. Assigning a value in a field definition like you try here:

#[derive(Serialize, Deserialize, Debug)]
pub struct AuthorizationDetails<T: DataFormat> {
    pub format: T::DataFormat::get_type(), // How to make this one possible??
    ...
}

is impossible. Do you want your format field to be a String that is populated with <T as DataFormat>::get_type() during deserialization?

Yes, exactly as you said.

Given that your format field is dependent on a different field (credential_definition), I don't think you'll find a way to avoid implementing Serialize and Deserialize on your type by hand.