如何用 ndarray 初始化一个常量矩阵?

son*_*ice 4 rust

我想有一个矩阵ndarray作为其他模块可用的常量。不幸的是,构造函数本身并不是一个常数函数。有没有办法绕过这个限制?

代码:

extern crate ndarray;

use ndarray::prelude::*;

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

fn main() {
    println!("{}", foo);
}
Run Code Online (Sandbox Code Playgroud)

错误:

extern crate ndarray;

use ndarray::prelude::*;

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

fn main() {
    println!("{}", foo);
}
Run Code Online (Sandbox Code Playgroud)

Pri*_*six 7

您可以声明一个不可变的静态变量而不是 const(因为 const 仅在编译时计算),然后使用lazy-static,即

用于在 Rust 中声明延迟评估的静态的宏。

运行您的函数并设置静态变量。

示例:游乐场

#[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);
}
Run Code Online (Sandbox Code Playgroud)

但是,它会要求您在使用变量之前取消引用它。