如何用 ndarray 初始化一个常量矩阵? [英] How to init a constant matrix with ndarray?
问题描述
我想在 ndarray
中有一个矩阵作为其他模块可用的常量.不幸的是,构造函数本身并不是一个常数函数.有没有办法绕过这个限制?
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?
代码:
extern crate ndarray;
use ndarray::prelude::*;
const foo: Array2<f32> = arr2(&[
[1.26, 0.09], [0.79, 0.92]
]);
fn main() {
println!("{}", foo);
}
错误:
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 | | ]);
| |__^
推荐答案
您可以声明一个不可变的静态变量而不是 const(因为 const 仅在编译时计算),然后使用 惰性静态,即
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
用于在 Rust 中声明延迟评估的静态的宏.
A macro for declaring lazily evaluated statics in Rust.
运行您的函数并设置静态变量.
to run your function and set the static variable.
示例:游乐场
#[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.
这篇关于如何用 ndarray 初始化一个常量矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!