I need a union to store a result that may be a closure or a variable. The problem is that closure sizes in Rust are not known at compile time so the union below stops my code from compiling.
How can I
- make my current code compile or
- find a way to have a type which can be either a variable or a closure?
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 information
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>,
| ^^^^ ^