2

I have this file utils.rs declaring a lazy_static like below:

extern crate geojson;
extern crate geo;

use self::geo::MultiPolygon;
use self::geojson::GeoJson;
use self::geojson::conversion::TryInto;

lazy_static! {
    pub static ref LAND_POLYGONS: MultiPolygon<f64> = {
        let input_string = include_str!("resources/land.geojson");
        let mut polygons: Vec<Polygon<f64>> = vec![];
        // ...
        // add some polygons here
        // ...
        MultiPolygon(polygons)
    };
}

Then in main.rs I try to use LAND_POLYGONS as follows:

#[macro_use]
extern crate lazy_static;

extern crate geo;

use self::geo::MultiPolygon;
use utils::LAND_POLYGONS;

fn main() -> Result<(), Box<Error>> {
    lazy_static::initialize(&LAND_POLYGONS);
    println!("{:?}", LAND_POLYGONS);

    Ok(())
}

Which produces the following compiler error:

error[E0277]: `utils::LAND_POLYGONS` doesn't implement `std::fmt::Debug`
  --> src/main.rs:30:22
   |
30 |     println!("{:?}", LAND_POLYGONS);
   |                      ^^^^^^^^^^^^^ `utils::LAND_POLYGONS` cannot be formatted using `:?`; add `#[derive(Debug)]` or manually implement `std::fmt::Debug`
   |
   = help: the trait `std::fmt::Debug` is not implemented for `utils::LAND_POLYGONS`
   = note: required by `std::fmt::Debug::fmt`

It seems that LAND_POLYGONS is loaded as an instance of its own type.

How to give LAND_POLYGONS its proper type, being a geo::MultiPolygon instead? As a side note, MultiPolygon does indeed definitely implement Debug.

The lazy_static documentation and examples make it look like this would already be the case without anything special to do.

Note: when putting all the above into one single main.rs file, the result is the same.

Jivan
  • 21,522
  • 15
  • 80
  • 131

1 Answers1

10

Under the hood, lazy_static generates a one-off struct type with a Deref implementation which gives you a reference to the actual value of the type you have specified.

Change your println statement to this:

println!("{:?}", *LAND_POLYGONS);
justinas
  • 6,287
  • 3
  • 26
  • 36
  • In case you're using the `dbg!` macro, you might need `&*LAND_POLYGONS` since it doesn't automatically borrow its argument like `println!` does. – user2468852 Apr 10 '19 at 18:36
  • Wouldn't `&*LAND_POLYGONS` result in a `&&MultiPolygon`, seeing how `deref()` returns a reference already? – justinas Apr 11 '19 at 12:56