Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: The generics trap
I decided to write my own N-D array implementation using generics for the number of dimensions:
pub struct ArrayNd<const N: usize, T> {
shape: [usize; N],
data: Vec<T>,
}
I wrote a maze generation algorithm and realized it cleanly generalizes to N dimensions. Examples:
10 x 10 (click for more details) 2 x 5 x 5 (click for more details)That's pretty cool! Let's let users specify these dimensions from the CLI, I thought.
I added clap
with a Vec<usize>
param and then it hit me. Since my type is "generic" and compiles to actual constant-size instances, I will not be able to do this.
A solution would be to remove the generic N
and rewrite the library to something like:
pub struct ArrayNd<T> {
shape: Vec<usize>,
data: Vec<T>,
}
That is a lot of work, loses compile-time checks, and is not even zero-cost.
I got an idea, why doesn't Rust provide a feature for "unspecified" or "run-time" generics? All unspecified parameters could be Box
ed and you could only have a single compiled type for "run-time" use cases. (Of course, there could also be "half-specified" types.)
I would like to hear your opinions:
Thanks for reading and replies.
4 posts - 4 participants
🏷️ Rust_feed