Hello,
I am trying to wire up a simple actor that is generic over the message type that it receives. I am getting the following error:
error[E0310]: the parameter type `T` may not live long enough
--> src/ib_data.rs:47:20
|
43 | impl<T: std::fmt::Debug + Send> ListenerHandle<T> {
| -- help: consider adding an explicit lifetime bound...: `T: 'static +`
...
47 | let join = tokio::spawn(listen(listener));
| ^^^^^^^^^^^^ ...so that the type `impl Future<Output = ()>` will meet its required lifetime bounds...
I am thinking that I must be missing something in my basic implementation if I am seeing this error. I was under the impression that 'static
means the type must live for the duration of the runtime but I don't want to have to keep messages around for any longer than they are needed.
I've seen similar errors involving ownership semantics when a closure sent to a thread, since that closure may live longer than the thread which launched it. This error seems quite similar, but since its the message type of a channel that is generic I am having a hard time reasoning through this one. Here is the code:
struct Listener<T> {
receiver: Receiver<T>,
}
impl<T: std::fmt::Debug + Send> Listener<T> {
fn new(receiver: Receiver<T>) -> Self {
Self { receiver }
}
}
async fn listen<T: std::fmt::Debug + Send>(mut listener: Listener<T>) {
while let Some(msg) = listener.receiver.recv().await {
println!("{msg:?}")
}
}
pub struct ListenerHandle<T> {
sender: Sender<T>,
join: JoinHandle<()>,
}
impl<T: std::fmt::Debug + Send> ListenerHandle<T> {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel(12);
let listener = Listener { receiver: receiver };
let join = tokio::spawn(listen(listener));
Self { sender, join }
}
}
Any pointers here would be greatly appreciated!
Dave