如果关闭的大小未知,如何将其存储在联合中?

问题描述

我需要一个联合来存储可能是闭包或变量的结果。问题在于,Rust中的关闭大小在编译时未知,因此下面的联合会阻止我的代码进行编译。

我怎么

  1. 编译当前代码
  2. 找到一种可以是变量或闭包的类型的方法吗?
union Value {
    variable: i32,function: dyn Fn(i32) -> i32,}

fn main() {}
error[E0658]: unions with non-`copy` fields are unstable
 --> src/main.rs:1:1
  |
1 | / union Value {
2 | |     variable: i32,3 | |     function: dyn Fn(i32) -> i32,4 | | }
  | |_^
  |
  = note: see issue #55149 <https://github.com/rust-lang/rust/issues/55149> for more @R_283_4045@ion

error[E0277]: the size for values of type `(dyn std::ops::Fn(i32) -> i32 + 'static)` cannot be kNown at compilation time
 --> src/main.rs:3:15
  |
3 |     function: dyn Fn(i32) -> i32,|               ^^^^^^^^^^^^^^^^^^ doesn't have a size kNown at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `(dyn std::ops::Fn(i32) -> i32 + 'static)`
  = note: no field of a union may have a dynamically sized type
  = help: change the field's type to have a statically kNown size
help: borrowed types always have a statically kNown size
  |
3 |     function: &dyn Fn(i32) -> i32,|               ^
help: the `Box` type always has a statically kNown size and allocates its contents in the heap
  |
3 |     function: Box<dyn Fn(i32) -> i32>,|               ^^^^                  ^

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)