Rust“不能使用依赖于类型中泛型参数的常量”

Jon*_*ght 6 rust

完整的代码游乐场

\n

我正在尝试编写一种数据结构,使其在不同维度上具有通用性。

\n

开头是:

\n
/// A field of adjacent sections in a given dimensionality.\n///  With 1, you have `|left|center|right|`.\n///  With 2 dimensions you have:\n///  ```\n///    up_left\xe2\x94\x82    up\xe2\x94\x82up_right\n///  \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n///       left\xe2\x94\x82center\xe2\x94\x82right\n///  \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xbc\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n///  down_left\xe2\x94\x82  down\xe2\x94\x82down_right\n///  ```\n///  Etc.\n#[derive(Debug)]\nstruct Adjacents<T, const D: u32>([T; size(D)])\n\nconst fn size(d: u32) -> usize { 3u32.pow(d) as usize }\n
Run Code Online (Sandbox Code Playgroud)\n

当尝试编写如下实现时:

\n
impl<T> Adjacents<T,1u32> { /*...*/ }\n
Run Code Online (Sandbox Code Playgroud)\n

我遇到严重警告(在少数情况下):

\n
warning: cannot use constants which depend on generic parameters in types\n  --> src/main.rs:26:9\n   |\n26 | impl<T> Adjacents<T,1u32> {\n   |         ^^^^^^^^^^^^^^^^^\n   |\n   = note: `#[warn(const_evaluatable_unchecked)]` on by default\n   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!\n   = note: for more information, see issue #76200 <https://github.com/rust-lang/rust/issues/76200>\n
Run Code Online (Sandbox Code Playgroud)\n

在我的用例中,某些功能可以跨存储数据类型()通用T,但不能跨维度(D)通用,因此我必须Adjacents<T,1u32>在整个过程中使用它似乎是不可避免的。

\n

更不用说D不依赖于T(我如何将其传达给编译器?)

\n

我在这里缺少什么?

\n
\n

完整代码在这里:

\n
warning: cannot use constants which depend on generic parameters in types\n  --> src/main.rs:26:9\n   |\n26 | impl<T> Adjacents<T,1u32> {\n   |         ^^^^^^^^^^^^^^^^^\n   |\n   = note: `#[warn(const_evaluatable_unchecked)]` on by default\n   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!\n   = note: for more information, see issue #76200 <https://github.com/rust-lang/rust/issues/76200>\n
Run Code Online (Sandbox Code Playgroud)\n