Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to init a constant matrix with ndarray? [duplicate]

Tags:

rust

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 | | ]);
  | |__^
like image 812
sonovice Avatar asked Jan 28 '23 20:01

sonovice


1 Answers

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.

like image 59
8176135 Avatar answered Feb 03 '23 14:02

8176135