Hi everyone,
let's assume I have code similar to this Playground. But instead of only having t1
and t2
, I have at least 8 more.
Is there a possible solution to not repeat myself over and over again? The problem is, that I need an else branch as well as at least two other, different branches (see the other_function
call).
Playground code
#![allow(unused_variables)]
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use std::borrow::Cow;
enum CustomError {
NotSupported,
}
#[async_trait]
trait Process {
type Output: Serialize;
type Input: DeserializeOwned + Send;
fn name(&self) -> Cow<str>;
async fn get_data(&mut self) -> Result<Self::Output, CustomError> {
Err(CustomError::NotSupported)
}
async fn set_data(&mut self, _data: Self::Input) -> Result<(), CustomError> {
Err(CustomError::NotSupported)
}
}
struct T1;
struct T2;
#[async_trait]
impl Process for T1 {
type Output = u32;
type Input = String;
fn name(&self) -> Cow<str> {
"T1".into()
}
async fn get_data(&mut self) -> Result<Self::Output, CustomError> {
Ok(3)
}
async fn set_data(&mut self, data: Self::Input) -> Result<(), CustomError> {
println!("{}", data);
Ok(())
}
}
#[async_trait]
impl Process for T2 {
type Output = String;
type Input = ();
fn name(&self) -> Cow<str> {
"T2".into()
}
async fn get_data(&mut self) -> Result<Self::Output, CustomError> {
Ok(String::from("Hi!"))
}
}
async fn send<T>(val: T) {
todo!()
}
async fn other_function() -> Result<(), ()> {
todo!()
}
#[tokio::main]
async fn main() {
let mut t1 = T1;
let mut t2 = T2;
loop {
tokio::select! {
other_val = other_function() => {
todo!()
}
Ok(val) = t1.get_data() => {
send(val).await
}
Ok(val) = t2.get_data() => {
send(val).await
}
else => {
eprintln!("What happened‽");
break;
}
}
}
}