I'm attempting to write a nested Container
, I encountered some difficulty while trying to get the size of each nested level. My question is how can I return the size of each nested level? Like, if the nesting level is 3, Container<Container<Container<T, 4>, 2>, 6>
then the return value would be [6, 2, 4]
. In c++, I can use std::index_sequence
in template to construct this. What should I do in rust? Here is my attempts, I was trying to use #![feature(specialization)]
to imitate, it works at the type level, but once I want to create a concrete value, this won't work anymore.
#![feature(specialization)]
Container<T, const N: usize> {
data: [T; N]
}
trait ContainerSize {
type SizeType;
//const SIZE: Self::Type;
}
impl<T> ContainerSize for T {
default type SizeType = (usize,);
//default const SIZE: Self::Type = (0,);
}
impl<T, const N: usize> ContainerSize for Container<T, N> {
type SizeType = (usize, <T as ContainerSize>::SizeType);
// const SIZE: Self::SizeType = (N, <T as ContainerSize>::SIZE);
}
fn main() {
use std::any::type_name;
type Nested = Container<Container<Container<f32, 2>, 3>, 4>;
println!("size type: {}", type_name::<<Container<Container<Container<f32, 2>, 3>, 4> as ContainerSize>::SizeType>());
// println!("size: {}", <Container<Container<Container<f32, 2>, 3>, 4> as ContainerSize>::SIZE);
}