Hi there, I’m new to Rust: most of my background is in C, and reading about the Rust type system I fell in love with the Enums and Structs rust has.
I was wondering if maybe I could use this power to model problems in a more direct way than what’s usually done. Specifically, I’m thinking about recursive structures.
In C - and as far as I understand - in Rust, if you want to have a recursive struct, you will have to use pointers so the compiler can figure out the size of the struct on compile time. But what if I know the struct has a base case, and the instances of this struct are defined with constants?
I wanted to use this to model some multidimensional geometry for a project I have:
In terms of points only, if we are in an M-dimensional space:
A 0-D hypercube is an M-D vector (also known as point)
A 1-D hypercube is two 0-D hypercubes (also known as line segment)
A 2-D hypercube is two 1-D hypercubes (also known as square)
A 3-D hypercube is two 2-D hypercubes (also known as cube)
…
A N-D hypercube is two (N-1)-D hypercubes.
I want to be able to define this struct in a recursive manner using generics, specifying the base case: 0-D.
// An M-Dimensional vector
struct vector<M : usize> {
coords: f64[M],
}
// A 0-dimensional hypercube living in an M-dimensional space
struct hypercube<0, M> {
point: vector<M>,
}
// An N-dimensional hypercube living in an M-dimensional space
struct hypercube<N : usize, M : usize> {
left: hypercube<N - 1, M>,
right: hypercube<N - 1, M>,
}
If then in my code I create a hypercube specifying a constant, the compiler should be able to unroll it using the base case and figure out the size of that struct. For example:
fn main() {
let cube_in_4d: hypercube<3, 4>; // This will have 2^3 = 8 4-dimensional vertices
}
I know Rust has generics, and this led me to find out that they are working in genericity over constants, and this is very close to what I’m thinking about, but my main issue is about defining a base case so we can have more complex, recursive structs, without losing the power of figuring them out on compile time.
Is there or will there be any way to do this?