我不是 const 泛型方面的專家,但是在嘗試涉及對 const 泛型進行操作的新型別實體化時,我嘗試了幾種不同的方法,但都遇到了問題,例如:當嘗試將這個 const 泛型結構中的基數從 to 遞增K時K 1.
// Given a Base<K> return a Base<K 1>
pub struct Base<const K:u32> {}
pub const fn base_bump<const K: u32, const L: u32>(b: Base<K>,) -> Base<L> {
const L : u32 = K 1;
Base::<L> {}
}
錯誤 :
error[E0401]: can't use generic parameters from outer function
--> src/main.rs:5:20
|
2 | pub const fn base_bump<const K: u32, const L: u32>(
| - const parameter from outer function
...
5 | const l: u32 = K 1;
| ^ use of generic parameter from outer function
For more information about this error, try `rustc --explain E0401`.
error: could not compile `playground` due to previous error
我的理解是 const 泛型的當前狀態拒絕const generic從其他const genericss 實體化 new ,因為const generics 在成為值之前是型別。愛荷華州,K在
fn foo<const K: u32> () {}
是一個型別而不是通常的 const 值,const K : u32 = 1;雖然我會在這里強烈提到錯誤訊息并沒有指向它背后的理性。
當我們嘗試這樣做時,會出現另一個問題:
pub struct Base<const K:u32> {}
// Given a Base<K> return a Base<K 1>
impl<const K : u32, const L: u32> Base<K> {
pub fn base_bump(&self) -> Base<L> {
todo!()
}
}
錯誤:
error[E0207]: the const parameter `L` is not constrained by the impl trait, self type, or predicates
--> src/lib.rs:3:27
|
3 | impl<const K : u32, const L: u32> Base<K> {
| ^ unconstrained const parameter
|
= note: expressions using a const parameter must map each value to a distinct output value
= note: proving the result of expressions other than the parameter are unique is not supported
有什么方法可以實作我在這里嘗試做的事情,還是應該放棄 const 泛型并使用常規欄位在這里定義基礎?
uj5u.com熱心網友回復:
我的理解是 const 泛型的當前狀態拒絕從其他 const 泛型實體化新的 const 泛型,因為 const 泛型在成為值之前是型別
這不是真的,但您的代碼存在多個問題。
首先,正如編譯器指出的那樣,const L 函式內部不能參考函式的泛型引數K。這是因為consts 是單獨編譯的,即使在函式內部也是如此(唯一的區別是函式外部的代碼無法訪問,即作用域)。
您應該嵌入計算:
pub const fn base_bump<const K: u32, const L: u32>(b: Base<K>) -> Base<L> {
Base::<{ K 1 }> {}
}
但這仍然存在多個問題。首先,您宣告您回傳Base的L是呼叫者選擇的,但實際上您回傳的是一個常量K 1而不是L。您需要像這樣宣告函式:
pub const fn base_bump<const K: u32>(b: Base<K>) -> Base<{ K 1 }> {
Base::<{ K 1 }> {}
}
但這與以下錯誤有關:
error: generic parameters may not be used in const operations
--> src/lib.rs:2:74
|
2 | pub const fn base_bump<const K: u32, const L: u32>(b: Base<K>) -> Base<{ K 1 }> {
| ^ cannot perform const operation using `K`
|
= help: const parameters may only be used as standalone arguments, i.e. `K`
error: generic parameters may not be used in const operations
--> src/lib.rs:3:14
|
3 | Base::<{ K 1 }> {}
| ^ cannot perform const operation using `K`
|
= help: const parameters may only be used as standalone arguments, i.e. `K`
因為這東西需要#![feature(generic_const_exprs)]。有了它,它可以作業,但會發出警告:
warning: the feature `generic_const_exprs` is incomplete and may not be safe to use and/or cause compiler crashes
--> src/lib.rs:1:12
|
1 | #![feature(generic_const_exprs)]
| ^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(incomplete_features)]` on by default
= note: see issue #76560 <https://github.com/rust-lang/rust/issues/76560> for more information
請參閱我的這個答案,了解為什么這個功能特別難。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/495751.html
上一篇:深層嵌套型別
