【发布时间】:2021-09-11 23:57:24
【问题描述】:
我有以下代码。我创建了一个 mpsc 通道,目标是将发送者传递给闭包,该闭包将注册为带有库的回调,然后将来自回调的数据发送到通道以供其他地方使用。
use std::sync::mpsc::channel;
use std::sync::mpsc::Sender;
use std::thread;
fn init(sender: Sender<&[u8]>) {
let handle_event = |x:i32, data:&[u8]| {
sender.send(data).unwrap();
};
//handle will be registered as callback with some library
//and used later in this thread
sender.send("Callback registered".as_bytes()).unwrap();
}
fn main() {
let (producer, bottle) = channel();
let child = thread::spawn(move ||init(producer));
for message in bottle {
//process data
}
let res = child.join();
}
但我在编译时收到以下错误:
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src/main.rs:7:21
|
7 | sender.send(data).unwrap();
| ^^^^
|
note: ...the reference is valid for the anonymous lifetime defined on the function body at 5:24...
--> src/main.rs:5:24
|
5 | fn init(sender: Sender<&[u8]>) {
| ^^^^^
note: ...but the borrowed content is only valid for the anonymous lifetime #1 defined on the body at 6:24
--> src/main.rs:6:24
|
6 | let handle_event = |x:i32, data:&[u8]| {
| ________________________^
7 | | sender.send(data).unwrap();
8 | | };
| |_________^
我该如何解决这个问题?我注册回调的那一行也会抛出这个错误。
explicit lifetime required in the type of `sender`
|
64 | .sample_cb(handle_event)
| ^^^^^^^^^ lifetime `'static` required
回调应该是这个特征
pub trait SampleCb: FnMut(i32, &[u8]) + 'static {}
我不确定第二个错误是否是由于第一个错误引起的,因为第一个错误无论是否注册为回调都会发生,如here
【问题讨论】:
标签: rust