8 ms·
Last night I was writing a blog post about how to use const generics. I included instructions on installing Rust Beta, and setting your directory to use the Bet
by adamch 6y ago
Last night I was writing a blog post about how to use const generics. I included instructions on installing Rust Beta, and setting your directory to use the Beta compiler instead of Stable. I started to write a disclaimer like "By the way, this will be stabilized in a future version of Rust, probably on..." and realized that const generics were being stabilized in less than 9 hours! So I removed all that stuff.
If you're interested in some concrete examples of using const generics to write faster code, my post on them is here: https://blog.adamchalmers.com/grids-2/ https://blog.adamchalmers.com/grids-2/
- reader_mode 6y agoThe good old Vector<T, N> from C++. For all the pain points C++ has, template metaprogramming was always so satisfying when you got it to work. Satisfying in "I feel really clever for solving this so generally and with no runtime overhead" way, but also being completely aware that another person reading the code and having to maintain it migh order a hit on me over darkweb.
- nayuki 6y agoDo you mean std::array<T,N>? ( https://en.cppreference.com/w/cpp/container/array https://en.cppreference.com/w/cpp/container/array )
- reader_mode 6y agoVector<T, N> an Matrix<T, N> is a fancy way to do small linear algebra types - like 2,3,4 vector and 3x3/4x4 matrix - you implement simple operations like add, multiply and dot products with loops and the compiler will unroll it and then you add some specific overloads for stuff like cross product, etc. Saves you having to reimplement it for every N. It's the simplest case of this kind of metaprogramming and feels good once you discover this kind of generalisation.
- nindalf 6y agoIt still says > This is gonna require some const generics stuff that isn't actually stabilized yet. This means, for the first time in my life, I'm going to have to use... Nightly Rust. I heard somewhere that it's stable now.
- adamch 6y agoRust 1.51 stabilized a lot of const generics use-cases, but there are still some advanced parts which are only on Nightly. For example, doing math with const generics, like an array [String; WIDTH * HEIGHT], still requires nightly.
- zackees 6y agoOne of my favorite data structures in C++ is InlineVector<T,N>. If the number of elements is <= N then it all fits in the preallocated space. This is great for keeping memory on the stack when N is small, yet allow heap memory overflow for larger N.
- withtypes 6y agoIn Rust there is smallvec https://docs.rs/crate/smallvec/ https://docs.rs/crate/smallvec/