我有这段代码在
impl App
内部运行,特别是在fn launch()
内部运行,就像这个例子一样:https://github.com/fltk-rs/fltk-rs/blob/master/fltk/examples/editor.rs
输出读取和写入必须在单独的线程中进行,这样 GUI 就不会死机。我已经尝试使用 MIO 和 tokio 以及子流程。对于普通线程,我在借用检查器方面遇到了问题,我太菜鸟了,无法解决。首先,这是程序的一个片段:
let mut child = Command::new(KOTLINC_PATH)
.arg("-script")
.arg(script_path)
.stdout(Stdio::piped())
// .stderr(Stdio::piped())
.spawn()
.expect("Could not execute script");
std::thread::spawn(move || {
let out = BufReader::new(
child.stdout.take().expect("Could not read from stdout."),
);
out.lines().for_each(|line| {
self.output.terminals[0].append(line.unwrap().as_str());
self.output.terminals[0].append("\n");
});
});
这里是错误:
borrowed data escapes outside of associated function
`self` escapes the associated function body here
main.rs(281, 23): `self` is a reference that is only valid in the associated function body
main.rs(281, 19): lifetime `'a` defined here
borrowed data escapes outside of associated function
argument requires that `'a` must outlive `'static`
我读过一些关于使用 Arc
let mut child = Command::new(KOTLINC_PATH)
.args(&["-script", script_path.clone().as_str()])
.stdout(Stdio::piped())
// .stderr(Stdio::piped())
.spawn()
.expect("Could not execute script");
let stdout = child
.stdout
.take()
.expect("Accessing stdout should never fail after passing Stdio::piped().");
let output_clone: Arc<Mutex<String>> = Arc::clone(&output);
thread::spawn(|| {
for line in BufReader::new(stdout).lines() {
let mut output_ref =
Mutex::into_inner(Arc::try_unwrap(output_clone).expect("1"))
.expect("2");
output_ref.push_str(line.unwrap().as_str());
output_ref.push_str("\n");
drop(output_ref);
}
});