Coming from a Scala background, a typical way of storing complex long lived immutable objects (like a big GeoJson MultiPolygon
loaded from a file) would be the following:
// in Helpers.scala
package helpers
object Helpers {
val landPolygons = loadFromGeoJsonFile("land-polygons.geojson")
val mountains = loadFromGeoJsonFile("mountains.geojson")
}
// and anywhere else in the app
import helpers.Helpers._
def myAwesomeFunc() = {
val myPoint = Point(23.0, 56.0)
val distFromLand = myPoint.distance(landPolygons)
val distFromMountains = myPoint.distance(mountains)
}
What would be the most adequate pattern to achieve the same functionality in Rust? The idea is that the values landPolygons
and mountains
have to be computed only once, and then available to use from anywhere in the whole application.
When trying to use a const
or static
declaration, the compiler outputs the following error:
error[E0015]: calls in constants are limited to struct and enum constructors
--> src/utils.rs:30:32
|
30 | const LAND_POLYGONS: GeoJson = include_str!("resources/land.geojson").parse::<GeoJson>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: a limited form of compile-time function evaluation is available on a nightly compiler via `const fn`
--> src/utils.rs:30:32
|
30 | const LAND_POLYGONS: GeoJson = include_str!("resources/land.geojson").parse::<GeoJson>().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^