【问题标题】:How to init a constant matrix with ndarray? [duplicate]如何用ndarray初始化一个常数矩阵? [复制]
【发布时间】:2018-12-13 00:57:30
【问题描述】:

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

代码:

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

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    用于在 Rust 中声明惰性求值静态的宏。

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

    示例: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);
    }
    

    这需要你在使用它之前取消引用变量。

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2019-11-29
      • 2018-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多