我在更换 proc 方面遇到了一些困难。使用 Invoke
可以工作,但我必须指定生命周期。为了能够将枚举发送到另一个线程,我必须使用 'static
和后来的 mem::transmute
来转换生命周期。不太吸引人。
另一方面,使用 FnOnce
会出现此错误:
<anon>:24:32: 24:33 error: cannot move a value of type for<'r> core::ops::FnOnce(&'r Type) + Send: the size of for<'r> core::ops::FnOnce(&'r Type) + Send cannot be statically determined [E0161]
如何正确替换proc?
#![feature(box_syntax)]
#![feature(std_misc)]
use std::mem;
use std::thunk::Invoke;
struct Type;
enum Message {
Handle(Box<Invoke<(&'static Type)> + Send>) //'
}
enum Message2 {
Handle(Box<FnOnce(&Type) + Send>)
}
pub fn main() {
let a = Type;
let handler = Message::Handle(box move |_| {});
let handler2 = Message2::Handle(box move |_| {});
match handler {
Message::Handle(f) => f.invoke(unsafe {mem::transmute(&a)})
}
match handler2 {
Message2::Handle(f) => f(&a)
}
}
最佳答案
使用 Thunk
怎么样? ?
#![feature(std_misc)]
use std::thunk::Thunk;
struct Type;
enum Message<'a> { //'
Handle(Thunk<'a, &'a Type, u8>)
}
pub fn main() {
let a = Type;
let handler = Message::Handle(Thunk::with_arg(move |_| 42));
let res = match handler {
Message::Handle(f) => f.invoke((&a))
};
println!("{}", res);
}
( playpen link )
In order to be able to send the enum to another thread I have to use 'static and later mem::transmute to cast the lifetime.
自 RFC 458着陆,thread::scoped
可以接受具有非'static
生命周期的闭包(和Fn*
特征)。需要注意的是,您必须确保线程在生命周期到期之前退出 - 否则您将引用无效内存!
使用 mem::transmute
可以让您忽略这一点,但代价是当该内存不再有效时程序崩溃。
关于rust - 如何用未装箱的闭包替换 proc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792072/