4

I would like to have a matrix in ndarray as a constant available for other modules. Unfortunately, the construction function itself is not a constant function. Is there any way around that restriction?

Code:

extern crate ndarray;

use ndarray::prelude::*;

const foo: Array2<f32> = arr2(&[
    [1.26, 0.09], [0.79, 0.92]
]);

fn main() {
    println!("{}", foo);
}

Error:

error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
 --> src\main.rs:5:26
  |
5 |   const foo: Array2<f32> = arr2(&[
  |  __________________________^
6 | |     [1.26, 0.09], [0.79, 0.92]
7 | | ]);
  | |__^
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
sonovice
  • 813
  • 2
  • 13
  • 27

1 Answers1

9

You can declare a immutable static variable instead of a const (since consts are compile time evaluated only), and then use lazy-static, which is

A macro for declaring lazily evaluated statics in Rust.

to run your function and set the static variable.

Example: Playground

#[macro_use]
extern crate lazy_static;

pub mod a_mod {
    lazy_static! {
        pub static ref FOO: ::std::time::SystemTime = ::std::time::SystemTime::now();
    }
}

fn main() {
    println!("{:?}", *a_mod::foo);
}

It would require you to deref the variable before you use it though.

weegee
  • 3,256
  • 2
  • 18
  • 32
8176135
  • 3,755
  • 3
  • 19
  • 42