Self 具有匿名生命周期,但需要满足静态生命周期要求

Mih*_*los 9 rust

我想在单独的线程上下载一个文件:

use http::StatusCode; // 0.2.1
use std::{fs::File, io::Write, path::Path, thread, time};
use reqwest; // 0.10.8

fn write_file(to_file: &str, response: reqwest::blocking::Response) -> std::io::Result<()> {
    let content = response.bytes().unwrap();
    let target_with_extension = Path::new(to_file);

    File::create(&target_with_extension)
        .expect("Unable to create file")
        .write_all(&content)?;
    Ok(())
}

pub struct Downloader;
impl Downloader {
    fn get(&self, from_url: &str, to_file: &str) -> std::io::Result<()> {
        let total_size: u64 = 1 * 1024 * 1024;

        let download_thread = std::thread::spawn(|| {
            let response = reqwest::blocking::get(from_url).unwrap();
            assert!(response.status() == StatusCode::OK);

            write_file(to_file, response).unwrap();
        });

        let fs = 0;
        while fs < total_size {
            let fs = std::fs::metadata("dua-v2.10.2-x86_64-unknown-linux-musl.tar.gz")?.len();
            println!("Downloaded {}", fs);
            thread::sleep(time::Duration::from_millis(500));
        }

        download_thread
            .join()
            .expect("The downloader thread panicked!");
        Ok(())
    }
}

fn main() {
    Downloader{}.get("https://github.com/Byron/dua-cli/releases/download/v2.10.2/dua-v2.10.2-x86_64-unknown-linux-musl.tar.gz", "dua-v2.10.2-x86_64-unknown-linux-musl.tar.gz");
}
Run Code Online (Sandbox Code Playgroud)

尝试编译时出现以下错误,我不知道绕过它的确切语法。在这里可以做什么?

error[E0621]: explicit lifetime required in the type of `from_url`
  --> src/main.rs:20:31
   |
17 |     fn get(&self, from_url: &str, to_file: &str) -> std::io::Result<()> {
   |                             ---- help: add explicit lifetime `'static` to the type of `from_url`: `&'static str`
...
20 |         let download_thread = std::thread::spawn(|| {
   |                               ^^^^^^^^^^^^^^^^^^ lifetime `'static` required

error[E0621]: explicit lifetime required in the type of `to_file`
  --> src/main.rs:20:31
   |
17 |     fn get(&self, from_url: &str, to_file: &str) -> std::io::Result<()> {
   |                                            ---- help: add explicit lifetime `'static` to the type of `to_file`: `&'static str`
...
20 |         let download_thread = std::thread::spawn(|| {
   |                               ^^^^^^^^^^^^^^^^^^ lifetime `'static` required
Run Code Online (Sandbox Code Playgroud)

归档时间:

查看次数:

4944 次

最近记录:

4 年,10 月 前