Generic arrays in Rust
Recently, I decided to try and "translate" the black hole simulator into Rust as an exercise. Initially I wanted to create a library implementing differential geometry, like tensor calculus, metric etc. I quickly encountered a problem.
Rust and arrays
Tensors are objects with some constant number of coordinates, depending on the dimension of the space they function in. For example, in an n-dimensional space, vectors have coordinates, rank-2 tensors have etc. Arrays are perfect for representing such objects.
Rust handles arrays without problems. An array of N elements of type T is written in Rust as [T; N]
. Everything would be fine, except for one tiny detail - I would like my code not to depend on the dimension of the space.
The problem
It is possible to define so-called generic types in Rust. They are datatypes that have internal details parametrized by some other type. For example, we could easily create a generic 3-dimensional vector:
1 2 3 |
struct Vector3<T> { coords: [T; 3] } |
What if we wanted to create an n-dimensional vector, though?
1 2 3 |
struct Vector<T,N> { coords: [T; N] // won't work } |
Nope. You can't express an integer type parameter in Rust.
It looked hopeless, but I accidentally stumbled upon some code that suggested the existence of a solution.
(more…)