Separate compilation for generics in Rust

C ++ is criticized because it lacks a separate compilation of templates. C ++ templates are compiled for (almost) every instance. What is the state of things for rust regarding a separate compilation of generics? I understand that it behaves like C ++, except that instances are cached during compilation of each box. It is right?

+7
c ++ generics rust
source share
3 answers

As far as I know, generics are stored in some serialized form in the box where they are defined. When used in another box (library or binary) they are created from this serialized form. Thus, they are monomorphized in the same way as C ++ templates, but they avoid the overhead of reanalyzing unnecessary code.

+3
source share

From the tutorial docs:

The Rust compiler very efficiently compiles common functions by monomorphizing them. Monomorphization is a bizarre name for a simple idea: create a separate copy of each common function on each call site, a copy that specializes in argument types and thus can be optimized specifically for them. In this regard, Rust breeds share similar performance characteristics with C ++ patterns. http://doc.rust-lang.org/0.11.0/tutorial.html#generics

EDIT: that really didn't answer your question, did it?

+2
source share

Common types and functions are modified. However, traits without generics can be used.

This is a common feature. He will be monomorphized.

fn get_length<T: Collection>(collection: &T) -> uint { collection.len() } 

This is an equivalent non-generic function. Only one copy of this function will be included in the binary.

 fn get_length(collection: &Collection) -> uint { collection.len() } 

Please note that we could not create a function that receives a Collection value by value because Collection is a sign and therefore does not have a specific size. In this case, a common function is required.

There are a few things you cannot do with generics and some things you cannot do with property references. Obviously, with trait references, you need a trait. In the case of generics, you cannot have a collection vector in which collections have different types (for example, you could not put Vec<int> and String in this vector), but you can use object references: a Vec<&Collection> may contain &Vec<int> and a &String .

+1
source share

All Articles