0

Can anyone tell what the lifetime error is in the following code? (simplified from my actual code) I've looked it over myself, but I can't figure out what is wrong or how to fix it.

use crate::hello_world_capnp::hello_world;
use capnp_rpc::{rpc_twoparty_capnp, twoparty, RpcSystem};
use futures::AsyncReadExt;
use futures::FutureExt;
use std;

pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tokio::task::LocalSet::new()
        .run_until(async move {
            let stream = tokio::net::TcpStream::connect("").await?;
            stream.set_nodelay(true)?;
            let (reader, writer) =
                tokio_util::compat::TokioAsyncReadCompatExt::compat(stream).split();
            let rpc_network = Box::new(twoparty::VatNetwork::new(
                reader,
                writer,
                rpc_twoparty_capnp::Side::Client,
                Default::default(),
            ));
            let mut rpc_system = RpcSystem::new(rpc_network, None);
            let hello_world: hello_world::Client =
                rpc_system.bootstrap(rpc_twoparty_capnp::Side::Server);

            tokio::task::spawn_local(Box::pin(rpc_system.map(|_| ())));

            let mut request = hello_world.say_hello_request();
            request.get().init_request().set_name("name");

            let reply = request.send().promise.await.unwrap();
            let img = reply
                .get()
                .unwrap()
                .get_reply()
                .unwrap()
                .get_image()
                .unwrap();

            show_image::run_context(move || {
                let image = ImageView::new(ImageInfo::rgb8(800, 533), img.clone());
            });
            Ok(())
        })
        .await
}

The compiler error is

`reply` does not live long enough

borrowed value does not live long enough
  • 1
    Please paste the full error message as printed by the compiler, including line numbers, code extracts and compiler suggestions. – Jmb Dec 17 '21 at 09:04

1 Answers1

1

I'm making some assumptions, as not all the code is given.

It seems like img has the type &[u8]. It borrows from reply. img is then used in the closure given to show_image::run_context(). The problem is that, looking at the docs for that function, it requires that the closure have the 'static lifetime. But the closure captures img, which is not 'static, and so you get the error.

A solution is to copy img to a new vec before run_context():

let img = reply
    .get()
    .unwrap()
    .get_reply()
    .unwrap()
    .get_image()
    .unwrap()
    .to_vec(); // <--

show_image::run_context(move || {
    let image = ImageView::new(ImageInfo::rgb8(800, 533), img); // <--
});
Brian Bowman
  • 892
  • 6
  • 9
  • That's right. `img` has the type `&[u8]`. I could clearly understand the way to solve this problem. Thank you for your quick and great answer! – Naoki Igarashi Dec 20 '21 at 06:51