如何克隆闭包,使它们的类型相同? [英] How do I clone a closure, so that their types are the same?

查看:97
本文介绍了如何克隆闭包,使它们的类型相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构,看起来像这样:

I have a struct which looks something like this:

pub struct MyStruct<F> where F: Fn(usize) -> f64 {
    field: usize,
    mapper: F,
    // fields omitted
}

如何为此结构实现 Clone

发现我可以复制函数体是:

One way I found by which I can copy the function body is:

let mapper = |x| (mystruct.mapper)(x);

但这会导致 mapper 类型比 mystruct.mapper 的类型。

But this results in mapper having a different type than that of mystruct.mapper.

playpen链接

推荐答案

您不能克隆关闭。实现 Clone 的唯一一个位置是编译器...而且它不是

You can't Clone closures. The only one in a position to implement Clone for a closure is the compiler... and it doesn't. So, you're kinda stuck.

这是一种方式:如果你有一个使用捕获的变量关闭,您可以通过 unsafe 代码强制复制。也就是说,一个更简单的方法在 点是接受 fn(usize) - > f64 ,因为它们没有捕获的环境(任何零大小的闭包都可以重写为函数), / code>。

There is one way around this, though: if you have a closure with no captured variables, you can force a copy via unsafe code. That said, a simpler approach at that point is to accept a fn(usize) -> f64 instead, since they don't have a captured environment (any zero-sized closure can be rewritten as a function), and are Copy.

这篇关于如何克隆闭包,使它们的类型相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆