如何使用 nalgebra 分配静态 `SMatrix`/`SVector`?

问题描述 投票:0回答:1

我想分配一个

SVector<f64, 7>
作为静态变量。似乎nalgebra 的库提供的构建器无法做到这一点,因为它们都不是
const
。有解决方法吗?为什么 Rust 不能使用非
const
限定函数来分配
const
变量?如果一个函数所操作的数据是
const
,为什么它是否
const
很重要?

这是我尝试过的(这无法编译):

const C5: SVector<f64, 7> = SVector::<f64, 7>::from_row_slice(&[
  5179.0 / 57600.0,
  0.0,
  7571.0 / 16695.0,
  393.0 / 640.0,
  -92097.0 / 339200.0,
  187.0 / 2100.0,
  1.0 / 40.0,
]);
rust constants builder nalgebra
1个回答
0
投票

我发现了一个const构造函数:

from_array_storage

use nalgebra::{ArrayStorage, SVector};

const C5: SVector<f64, 7> = SVector::<f64, 7>::from_array_storage(ArrayStorage([[
    5179.0 / 57600.0,
    0.0,
    7571.0 / 16695.0,
    393.0 / 640.0,
    -92097.0 / 339200.0,
    187.0 / 2100.0,
    1.0 / 40.0,
]]));

对于您的其他问题:

  • Rust 同时具有
    const
    static
    值。如果你需要一个无法在编译时构造的全局值,那么你可以使用
    static
    ,通常使用类似
    Lazy
    (未来 Rust 标准库中的
    LazyLock
    )或
     thread_local
  • Rust 不具备将非 const 函数提升为 const 的能力。如果可以的话,那么对函数内部的更改可能是一个重大更改。然而,Rust 会在编译时评估
    let
    static
    绑定(如果有能力)并认为这有利于优化。
  • 仅仅因为参数是 const 并不意味着函数内的所有操作都是 const。通常这是分配。
© www.soinside.com 2019 - 2024. All rights reserved.