Search code examples
rustheap-memorysmart-pointersstack-memory

How to do pattern matching with boxed enum?


i have an enum where i have to perform pattern matching. But since i am running the program on VM which has limited stack memory ( < 4Kb ), i allocated the enum on the heap using Box. But while performing pattern matching, i have to dereference it which causes it to get allocated on stack which i dont need. Is it possible to perform pattern matching on Boxed values?

I want to achieve something like below.

pub enum MyEnum {
  A,
  B,
}

let a = Box::new(MyEnum::A);
let value = match a {
  MyEnum::A => 1,
  MyEnum::B => 2 
}

This is the error that i get

error[E0308]: mismatched types
   --> src/entrypoint.rs:119:9
    |
118 |     match a {
    |           ---
    |           |
    |           this expression has type `Box<MyEnum>`
    |           help: consider dereferencing the boxed value: `*a`
119 |         MyEnum::A => 1,
    |         ^^^^^^^^^^^^^^^ expected struct `Box`, found enum `MyEnum`
    |
    = note: expected struct `Box<MyEnum>`
                 found enum `MyEnum`

I tried dereferencing it as the compiler suggested, but since it allocated on stack while dereferencing, i could not use it. I want to match the enum without dereferencing it.


Solution

  • You can match on references too. This will simply reborrow boxed value and allocate at most a pointer on the stack.

    pub enum MyEnum {
      A,
      B,
    }
    
    let a = Box::new(MyEnum::A);
    let value = match &*a {
      &MyEnum::A => 1,
      &MyEnum::B => 2 
    };