Generic struct into and out of function

I'm trying to write a function that takes one of many predefined structs and deserializes data from a string into them. I then need to return the struct from the function. I don't believe I'm allowed to return a generic type from a function so tried wrapping it in a enum and pass it into the function but it doesn't like it. Am I doing this wrong or is there a better way to do this ?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6894ab5fdcc647b6d89867bf0cc76132

Here is a good starting point:

use serde::{Deserialize, Serialize};

#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Debug)]
struct SessionUserLogon {
    user_id: String,
    password: String,
    language: Option<String>,
    eleveate: Option<String>,
    mobile_device_id: Option<String>,
}

#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize, Debug)]
struct SessionUserLogout {
    session_id: String,
}

fn main() {
    let body = r#" {"sessionId": "foobar"} "#;
    let logon_out: SessionUserLogout = serde_json::from_str(body).unwrap();
    println!("{:?}", logon_out);
    
    
    let body = r#" {"userId": "a", "password":"foobar"} "#;
    let logon: SessionUserLogon = serde_json::from_str(body).unwrap();
    println!("{:?}", logon);
}

playground

Why so? Check this playground for a possible approach.

@Cerber-Ursi thanks that is what I'm after. Im struggling abit with the lifetimes in your example though as I'm reading client input into body which isn't <'static>. Any hints on how I should set the lifetimes for a String.

Replacing Deserialize<'static> with serde::de::DeserializeOwned works,

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.