0

I don't know how to properly extract data from Box. I made a very simple demo with a minimal example:

struct Amsterdam {
    population: i32,
}

enum City {
    Amsterdam(Amsterdam),
}

enum Country {
    Netherlands(Box<City>),
}

fn main() {
    let my_city = Country::Netherlands(Box::new(City::Amsterdam(Amsterdam { population: 821752 })));

    if let Country::Netherlands(City::Amsterdam(city_data, ..)) = my_city {
        println!("{}", city_data.population);
    };
}

Error:

error[E0308]: mismatched types
  --> src/main.rs:16:33
   |
16 |     if let Country::Netherlands(City::Amsterdam(city_data, ..)) = my_city {
   |                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    ------- this expression has type `Country`
   |                                 |
   |                                 expected `Box<City>`, found `City`
   |
   = note: expected struct `Box<City>`
                found enum `City`

Playground

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Roman
  • 175
  • 2
  • 3
  • 15

0 Answers0