The library I'm working on allows a user to create channels that read and write channel messages to and from the same TCP connection. I am using the
async-channels crate for the channels.
The library forces a user to create a new channel for every different type, and it maintains a HashMap of the TypeId for every type and its corresponding channel. In the background, the library serializes all the different messages into bytes alongside its TypeId and writes that data to the TCP stream. On reading from the stream, it extracts the TypeId and bytes, looks up the channel from the Hashmap using the TypeId as the key, and then sends the message on the channel.
My issue is that I don't know how to store differently-typed values in the Hashmap. One relation could be
TypeId -> (Sender<String, Receiver<String>), while another could be
TypeId -> (Sender<CustomEnum>, Receiver<CustomEnum>).
I tried defining traits like GenericSender and GenericReceiver that implemented the same
try_recv functions as Sender and Receiver structs. But I quickly learned this was not feasible, as
send for example takes a generic parameter
T, which would not allow me to use GenericSender or GenericReceiver as trait objects.
What is the idiomatic way of solving this problem?