Static lifetime in reqwest crate

I had fun learning rust recently, until I encoutered this problem of lifetime.

The thing is, I just want to make a script that sends a user input to saucenao.com and get the result. I thought this problem was very simple until the compiler told me &args[1] does not live long enough because the argument of .text method has a static lifetime and that made me struggle a whole night.

use reqwest::blocking;
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    getsauce(&args[1]);
}

fn getsauce(url: &'static str) {
    let form = blocking::multipart::Form::new()
        .text("url", url);
    let client = blocking::Client::new();
    let res = client.post("https://saucenao.com/search.php")
        .multipart(form)
        .send().unwrap();

    println!("{}", res.text().unwrap());
}

You can turn it into a String:

fn main() {
    let args: Vec<String> = env::args().collect();
    getsauce(&args[1]);
}

fn getsauce(url: &str) {
    let form = blocking::multipart::Form::new()
        .text("url", url.to_string());
    let client = blocking::Client::new();
    let res = client.post("https://saucenao.com/search.php")
        .multipart(form)
        .send()
        .unwrap();

    println!("{}", res.text().unwrap());
}

text wants an Into<Cow<'static, str>>, which is basically either a string literal or a String, so since you can't guarantee the reference will live for the rest of the program you can just give it something it can own.

1 Like

Thank you so much. I didn't know &'static str can also means a String.

It can't - those are two different types. text doesn't need a &'static str, though, it needs an Into<Cow<'static, str>>, which happens to be implemented by both &'static str and String.

1 Like