1

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

  1. make my current code compile or
  2. 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>,
  |               ^^^^                  ^
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Caspian Ahlberg
  • 934
  • 10
  • 19
  • 1
    Why a union instead of an enum? – Shepmaster Oct 19 '20 at 18:20
  • 1
    Your question might be answered by the answers of [How do I store a closure in a struct in Rust?](https://stackoverflow.com/q/27831944/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Oct 19 '20 at 18:20
  • @Shepmaster The question that you linked answered my question. You can mark this one as already answered. – Caspian Ahlberg Oct 19 '20 at 19:08

0 Answers0