Suppose I have a thread, that listens for incoming data. Data might be the serialization of two different types, say 'request' or 'response'. However we can not know in advance, which one it is. So I'm not sure how to deserialize the stream properly. The following example illustrates the situation:
#[derive(Serialize, Deserialize, Debug)]
struct Request {
type : different_from_request_type
}
#[derive(Serialize, Deserialize, Debug)]
struct Response {
type: different_from_response_type
}
// function main listens for incomming data, where data can be the serialization of type request OR response, but main() doesn't know which one it is...
fn main() {
let l = net::TcpListener::bind("somewhere").unwrap();
thread::spawn(||{
let l = l;
for stream in l.incoming() {
let mut stream = stream.unwrap();
let read_stream = stream.try_clone().unwrap();
let mut de = serde::json::Deserializer::new(read_stream.bytes()).unwrap();
// Ok. Now I would like to actually deserialize this either into request or
// response. But I don't know if it is the serialization
// of response or request. They are different.
// IF I knew in advance, I would just write either
// let request = Request::deserialize(&mut de).unwrap();
// or
// let response = Response::deserialize(&mut de).unwrap();
// But I don't know. So how can I handle this?
}
});
}