Hey guys, I used tokio + tonic to build a simple search service. However, inside the tokio::spawn
future, I cannot use the self
directly.
async fn search(&self, request: Request<Streaming<SearchRequest>>) -> Result<Response<Self::SearchStream>, Status> {
let mut req_stream = request.into_inner();
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
while let Some(result) = req_stream.next().await {
match result {
Ok(r) => {
if let Err(e) = self.data_store.search(&tx, r.query.as_str(), r.case_sensitive, r.with_pos) {
if let Err(_) = tx.send(Err(Status::internal(e.to_string()))) {
break;
}
}
}
Err(status) => {
if let Err(_) = tx.send(Err(status)) {
break;
}
}
}
}
});
let resp_stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
Ok(Response::new(Box::pin(resp_stream)))
}
The compiler complained:
$ cargo b
Compiling search-service v0.1.0 (/home/foo/work/search-service)
error[E0759]: `self` has lifetime `'life0` but it needs to satisfy a `'static` lifetime requirement
--> src/server.rs:36:22
|
36 | async fn search(&self, request: Request<Streaming<SearchRequest>>) -> Result<Response<Self::SearchStream>, Status> {
| ^^^^ this data with lifetime `'life0`...
...
40 | tokio::spawn(async move {
| ------------ ...is used and required to live as long as `'static` here
|
note: `'static` lifetime requirement introduced by this bound
--> /home/foo/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.20.1/src/task/spawn.rs:127:28
|
127 | T: Future + Send + 'static,
| ^^^^^^^
For more information about this error, try `rustc --explain E0759`.
error: could not compile `search-service` due to previous error
I have no idea how to solve this, I'm a Rust newbie.