rust - 如何用未装箱的闭包替换 proc?

标签 rust

我在更换 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/

相关文章:

unit-testing - 编写集成测试时如何访问主包中的函数?

logging - 运行 cargo test 时如何设置日志级别?

rust - 尝试实现查找或插入时 HashMap 借用问题

rust - 如何在 Rust 中为 Option<U> 实现 From<T>?

rust - 使用堆栈实现深度优先搜索

rust - 为 Rust 中的特征提供类似继承的行为

tcp - 优雅退出 TcpListener.incoming()

rust - 线程局部 RefCell 作为 Rust 中局部变量的替换

rust - 在 Rust 中,如何在向量的向量中合并两个子向量?

rust - 临时值的生命周期不够长