Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can associated constants be used to initialize the length of fixed size arrays?

Tags:

rust

In C++, you have the ability to pass integrals inside templates

std::array<int, 3> arr; //fixed size array of 3

I know that Rust has built in support for this, but what if I wanted to create something like linear algebra vector library?

struct Vec<T, size: usize> {
    data: [T; size],
}

type Vec3f = Vec<f32, 3>;
type Vec4f = Vec<f32, 4>;

This is currently what I do in D. I have heard that Rust now has Associated Constants.

I haven't used Rust in a long time but this doesn't seem to address this problem at all or have I missed something?

As far as I can see, associated constants are only available in traits and that would mean I would still have to create N vector types by hand.

like image 441
Maik Klein Avatar asked Oct 23 '25 15:10

Maik Klein


2 Answers

No, associated constants don't help and aren't intended to. Associated anything are outputs while use cases such as the one in the question want inputs. One could in principle construct something out of type parameters and a trait with associated constants (at least, as soon as you can use associated constants of type parameters — sadly that doesn't work yet). But that has terrible ergonomics, not much better than existing hacks like typenum.

Integer type parameters are highly desired since, as you noticed, they enable numerous things that aren't really feasible in current Rust. People talk about this and plan for it but it's not there yet.

Integer type parameters are not supported as of now, however there's an RFC for that IIRC, and a long-standing discussion.

You could use typenum crate in the meanwhile.

like image 34
aldanor Avatar answered Oct 25 '25 15:10

aldanor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!