How can I telll compiler that this reference is static?

I am trying to write a program in which I store a reference to reqwest::Client in a struct, then use it asynchronously in tokio runtime. Compiler keeps complaining that client dropped here while still borrowed [E0597] and argument requires that client is borrowed for 'static [E0597], even though I wait for the async thread to finish with handle.await.unwrap().

Is there any way I can achieve this (storing and using reqwest::Client as a reference) without moving it, which will also require cloning it when I have multiple such structs? In my undrestanding reqwest::Client is immutable and is supposed to live as long as the application itself; so it shouldn't be a problem storing and passing around a reference to it.

    #[tokio::main]
    async fn main() {
        let user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0";
    
        let client = reqwest::Client::builder()
            .user_agent(user_agent)
            .build()
            .unwrap();
    
        let (tx, mut rx): (
            Sender<Message<WikiResult>>,
            Receiver<Message<WikiResult>>,
        ) = mpsc::channel(1024);
    
        let wiki = Wiki::new(&client, tx.clone());
    
        let handle = tokio::spawn(async move {
            if let Err(err) = wiki.search_articles().await {
                println!(
                    "Encountered fatal error when searching: {:#?}",
                    err
                );
            };
        });
    
        while let Some(group) = rx.recv().await {
            match group {
                Message::Error(err) => {
                    println!("Encountered error when searching articles: {:#?}", err)
                }
                Message::ResultItem(article) => {
                    println!("Found article: {:#?}", article);
                }
            }
        }
    
        handle.await.unwrap();
    }

Try Box::leak

let client = Box::new(client);
let client: &'static reqwest::Client = Box::leak(client);

Also the reqwest::Client store its internal states in Arc, so clone it when needed can take advantage of connection pool.

Thank you for responding!
Box::leak seems to be what I was asking for. I didn't pay enough attention in reqwest's docs, looks like I should just pass client.clone() to my struct instead of trying to pass a reference.

1 Like

Cloning the client is the right solution here.

2 Likes