返回基于const泛型的非数组类型



我知道可以根据const泛型返回不同的类型,例如fn example<const N:usize>() -> [u8;N]

是否有可能返回基于const泛型的泛型类型,例如fn example<const N:usize>() -> N::Type?

我目前最好的尝试(操场):

struct MyStruct {
first: First,
second: Second,
third: Third
}
impl MyStruct {
fn first(&self) -> &First {
&self.first
}
fn second(&self) -> &Second {
&self.second
}
fn third(&self) -> &Third {
&self.third
}
}
#[derive(Debug)]
struct First(u16);
#[derive(Debug)]
struct Second(u8);
#[derive(Debug)]
struct Third(u32);
trait ConstIndex<const INDEX:usize> {
type Output;
fn index(&self) -> &Self::Output;
}
impl ConstIndex<0> for MyStruct {
type Output = First;
fn index(&self) -> &Self::Output {
self.first()
}
}
impl ConstIndex<1> for MyStruct {
type Output = Second;
fn index(&self) -> &Self::Output {
self.second()
}
}
impl ConstIndex<2> for MyStruct {
type Output = Third;
fn index(&self) -> &Self::Output {
self.third()
}
}
fn main() {
let my_struct = MyStruct { first: First(123), second: Second(242), third: Third(789) };
let one = ConstIndex::<0>::index(&my_struct);
println!("one: {:?}",one);
let two = ConstIndex::<1>::index(&my_struct);
println!("two: {:?}",two);
let three = ConstIndex::<2>::index(&my_struct);
println!("three: {:?}",three);

}

这里索引的语法很尴尬,例如ConstIndex::<2>::index(&my_struct).

最好使用my_struct.cindex::<0>()这样的语法。

我想你在找这样的东西:

游乐场

struct MyStruct {
first: First,
second: Second,
third: Third
}
impl MyStruct {
fn first(&self) -> &First {
&self.first
}
fn second(&self) -> &Second {
&self.second
}
fn third(&self) -> &Third {
&self.third
}

fn cindex<const N:usize>(&self) -> &<MyStruct as ConstIndex<N>>::Output
where MyStruct : ConstIndex<N>
{
<MyStruct as ConstIndex<N>>::index(self)
}
}
#[derive(Debug)]
struct First(u16);
#[derive(Debug)]
struct Second(u8);
#[derive(Debug)]
struct Third(u32);
trait ConstIndex<const INDEX:usize> {
type Output;
fn index(&self) -> &Self::Output;
}
impl ConstIndex<0> for MyStruct {
type Output = First;
fn index(&self) -> &Self::Output {
self.first()
}
}
impl ConstIndex<1> for MyStruct {
type Output = Second;
fn index(&self) -> &Self::Output {
self.second()
}
}
impl ConstIndex<2> for MyStruct {
type Output = Third;
fn index(&self) -> &Self::Output {
self.third()
}
}
fn main() {
let my_struct = MyStruct { first: First(123), second: Second(242), third: Third(789) };
let one = ConstIndex::<0>::index(&my_struct);
println!("one: {:?}",one);
let two = ConstIndex::<1>::index(&my_struct);
println!("two: {:?}",two);
let three = ConstIndex::<2>::index(&my_struct);
println!("three: {:?}",three);

let one_2 = my_struct.cindex::<0>();
println!("one: {:?}",one_2);
let two_2 = my_struct.cindex::<1>();
let three_2 = my_struct.cindex::<2>();
}

相关内容

  • 没有找到相关文章

最新更新