Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant values in Rust generics [duplicate]

Does Rust language support constant values in generic code similar to c++ way? Seems that the language overview doesn't advertise it. Parameterizing types with constants in C++ allows to create objects with preallocated buffers of different size depending on client's needs (types like stlsoft::auto_buffer).
If not, then what is the best practices to implement similar designs in Rust?

like image 734
tivadj Avatar asked Feb 11 '13 16:02

tivadj


1 Answers

No, this is not supported in a type-safe way. We would need type-level numeric literals, like GHC recently added, for that.

However, you can use Rust macros. With a macro you can create "templates" that are parameterized over arbitrary expressions, including constants, which would allow you to do what you want here. Note that you may find bugs and limitations in the macro system if you try this at the moment.

like image 140
Patrick Walton Avatar answered Nov 16 '22 03:11

Patrick Walton