在這個操場上,我想只為具有某個屬性的 const 泛型引數實作一種方法:https ://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=3e4d5f9f27912d032308a390a56f5f94
我正在使用一個零大小的型別并向它添加一個方法:
pub struct Resource<const N: usize> {}
impl<const N: usize> Resource<N> {
const fn shorten<const M: usize>(self) -> Resource<M>
where
[(); N - M]:, // type existence only ensured if N >= M
{
// Runtime checks, though they should not be needed
if M <= N {
Resource {}
} else {
panic!("Resources can only be shortened")
}
}
}
這個想法是一個Resource<N>型別可以縮短為Resource<M>if N >= M。
但是,當我這樣使用它時:
pub fn bar<const N: usize>(
resource: Resource<N>,
) -> Result<((), Resource<{ N - 1 }>), Box<dyn std::error::Error>>
where
[(); N - 1]:,
{
Ok(((), resource.shorten::<{ N - 1 }>()))
}
我收到以下編譯器錯誤:
error: unconstrained generic constant
--> src/main.rs:43:22
|
43 | Ok(((), resource.shorten::<{ N - 1 }>()))
| ^^^^^^^
|
= help: try adding a `where` bound using this expression: `where [(); N - M]:`
note: required by a bound in `Resource::<N>::shorten`
--> src/main.rs:8:14
|
6 | const fn shorten<const M: usize>(self) -> Resource<M>
| ------- required by a bound in this
7 | where
8 | [(); N - M]:, // type existence only ensured if N >= M
| ^^^^^ required by this bound in `Resource::<N>::shorten`
我了解(并在其他在線資源中發現)編譯器建議where可能具有誤導性(因為它不是常用功能)。忽略這個建議,我不知道為什么以及在哪里首先需要這個界限。
在bar中,shorten呼叫在Resource<N>(clear from parameter) 上執行以回傳Resource<{N - 1}>(clear from turbo-fish)。我錯過了什么?
很高興聽到更有經驗的 Rustaceans 的一些想法。
uj5u.com熱心網友回復:
編譯器不分析運算式(通常這也是不可能的)。它進行逐字替換。如果要編譯此代碼,則需要將Nand替換M為使用的實際值:
pub fn foo<const N: usize>(
resource: Resource<N>,
) -> Result<((), Resource<{ N - 2 }>), Box<dyn std::error::Error>>
where
[(); N - (N - 1)]:,
[(); (N - 1) - (N - 2)]:,
{
let (baz, resource): ((), Resource<{ N - 1 }>) = bar::<{ N }>(resource)?;
resource.dbg();
// new resource is N-1; returning it as N-2 should work, as it is smaller
// 'shorten<M>' does not exist, if there is no conversion possible
Ok((baz, resource.shorten::<{ N - 2 }>()))
}
pub fn bar<const N: usize>(
resource: Resource<N>,
) -> Result<((), Resource<{ N - 1 }>), Box<dyn std::error::Error>>
where
[(); N - (N - 1)]:,
{
Ok(((), resource.shorten::<{ N - 1 }>()))
}
游樂場。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523369.html
標籤:仿制药锈常数依赖型
上一篇:將資料成員分配給另一個泛型型別的資料成員的正確方法是什么
下一篇:C#抽象類中的多個泛型型別
