簡體   English   中英

用作參數時,“閉包可能比當前函數壽命更長”

[英]“closure may outlive the current function” while used as a parameter

我正在嘗試將 function 作為參數傳遞並在線程內調用它。 這是我要運行的代碼:

use std::thread;

pub struct Image {
    pub data: Vec<u8>,
}

pub trait ImageHandler {
    fn get_image(&self) -> Option<Image>;
}

pub struct Window {
    pub id: usize,
}

impl ImageHandler for Window {
    fn get_image(&self) -> Option<Image> {
        None
    }
}

fn test(func: impl Fn() -> Option<Image> + Sync + Send + 'static) -> thread::JoinHandle<()> {
    thread::spawn(move || {
        let _image = func().unwrap();
    })
}

fn main() {
    let window = Window { id: 0 };
    test(&|| window.get_image());
}

我收到以下錯誤:

error[E0373]: closure may outlive the current function, but it borrows `window`, which is owned by the current function
  --> src/main.rs:30:11
   |
30 |     test(&|| window.get_image());
   |           ^^ ------ `window` is borrowed here
   |           |
   |           may outlive borrowed value `window`
   |
note: function requires argument type to outlive `'static`
  --> src/main.rs:30:5
   |
30 |     test(&|| window.get_image());
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `window` (and any other referenced variables), use the `move` keyword
   |
30 |     test(&move || window.get_image());
   |           ^^^^^^^

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:30:11
   |
30 |     test(&|| window.get_image());
   |     ------^^^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
   |     |     |
   |     |     creates a temporary which is freed while still in use
   |     argument requires that borrow lasts for `'static`

我想Fn應該是 static 用於將其發送到線程但是當我將其生命周期更改為'static時,它會抱怨。 另外我不知道是否可以使用ImageHandler作為參數。 我想不通。

如果閉包可以比當前線程壽命更長,它應該擁有它需要的變量的所有權:

fn main() {
    let window = Window { id: 0 };
    test(move || window.get_image());
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9cbf953b79e80e280156688d083f94fb有操場。

但是,(我猜)這只是一個玩具示例,此修復可能適用於您的實際用例,也可能不適用於您的實際用例。 如果它變得更復雜,您可以嘗試讓編譯器相信您知道閉包不會超過當前線程(可能使用輔助板條箱)或訴諸其他技術。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM