Not sure what to put in the title. My example code looks like this:
use rand::Rng;
use serde::Deserialize;
use serde_json::json;
#[derive(Deserialize, Debug)]
#[serde(tag = "id")]
enum FooBar {
#[serde(rename = "1")]
Foo(Foo),
#[serde(rename = "2")]
Bar(Bar),
}
#[derive(Deserialize, Debug, PartialEq)]
struct Foo {
foo: String,
}
#[derive(Deserialize, Debug, PartialEq)]
struct Bar {
bar: String,
}
// Returns message with random id
fn read() -> FooBar {
let messages = [
json!({"id":"1","foo":"Foo"}),
json!({"id":"2","bar":"Bar"}),
];
let mut rng = rand::thread_rng();
let number: usize = rng.gen_range(0..2);
let random_message = messages.get(number).unwrap().clone();
serde_json::from_value::<FooBar>(random_message).unwrap()
}
// Should call read() until it gets a message of type T and return it
fn wait<T>() -> T {
loop {
let _message: FooBar = read();
todo!("If message is the type of T, return it.")
}
}
fn main() {
let foo_or_bar = read();
println!("Foo or Bar: {:?}", foo_or_bar);
let foo: Foo = wait();
println!("Foo: {:?}", foo.foo);
let bar: Bar = wait();
println!("Foo: {:?}", bar.bar);
}
read currently returns one of the two messages as FooBar, which works fine. Now I want wait to call read until it returns the correct message depending on the generic. Is something like that possible?