When I try the code bellow (this is a small example to reproduce my problem), I have this error from the compiler:
error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`Message`)
use serde::{Serialize, Deserialize};
// A simple struct that can be serialized and deserialized
#[derive(Debug, Serialize, Deserialize)]
struct MyStruct(u64, String);
// A struct Message that can be converted into any deserializable object
struct Message(String);
impl<T: for<'a> Deserialize<'a>> TryFrom<Message> for T {
type Error = serde_json::Error;
fn try_from(value: Message) -> Result<Self, Self::Error> {
serde_json::from_str(value.0)
}
}
fn main() {
let my_message = Message(
serde_json::to_string(MyStruct(123, "Hello".to_string()))
);
let result_from_message = MyStruct::TryFrom(my_message).unwrap();
println!("{result_from_message:?}");
}
I do not quite understand it, may I have some help?
Thanks for your help everyone, I think I get it now!
I finally rethink my code this way:
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct MyStruct(u64, String);
struct Message(String);
impl Message {
fn into<T: DeserializeOwned>(self) -> Result<T, serde_json::Error> {
serde_json::from_str(&self.0)
}
}
fn main() {
let message =
Message(serde_json::to_string(&MyStruct(58, "Hello, World!".to_string())).unwrap());
let my_struct = message.into::<MyStruct>().unwrap();
println!("{my_struct:?}");
}