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

ⅰ亾dé卋堺 提交于 2021-02-07 18:41:32

问题


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 | | ]);
  | |__^

回答1:


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; // 1.0.1;

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.



来源:https://stackoverflow.com/questions/51176126/how-to-init-a-constant-matrix-with-ndarray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!