Why does there seem to be no need of a Rust template library?


#1

I know C++'s library is mainly its template library. Why is rust so different in this respect?


#2

How do std and core not serve this role? I see resizable vectors, hash maps, ref-counted pointers, iterators…


#3

For example, a linked list node can be any type. In C++, lists with different types of node are implemented by a template and acctually if there are ten different types there will be ten copies of the source code using that template. In Rust, there is only one copy, and it can deal with all different types of nodes. I am just curious how Rust achieves to do that.


#4

Rust’s generics have a unique representation for each type used after a process called monomorphization takes place. The “copies” are in the compiler representation of the code (ie IR). C++ templates are morally equivalent in this regard because you don’t see the template instantiations in the source code. The major difference is that C++ templates are duck typed, whereas Rust generics are not; the closer analog to Rust generics would be C++ Concepts.


#5

Compile-time monomorphization of generic functions and methods in Rust produces one instantiation of the function/method in the binary for (more or less) each distinct specialization used in the program, just as template specializations in C++ lead to multiple instantiations of templated functions, methods, and classes.


#6

I think std/core are Rust’s standard template library. If you look at most of the data structures in the standard library you’ll see that they’re completely generic over their contents. The word “generic” and “template” are synonyms for the same thing (compile-time monomorphization).

I think the main reason you don’t see different implementations depending on the concrete type (e.g. a more efficient Vec<bool> type) is because we don’t (yet!) have specialization.