Why Generic Types?

• Don't Repeat Yourself (DRY): Don't write the same code twice with slight changes; don't copy-paste

• Let's make a stack.

playground

• This is terrible. I spent a ton of time editing this example:

• It was easy to forget to fix up everything when copy-pasting

Going Generic

• A "generic type" is a type symbol used as a placeholder for an empty type. Of course, the type must eventually be filled in

• By (ugly) convention, Rust generic types are usually single capital letters

• Angle brackets are used to fill in a generic with a particular type, as with Vec in the playground

• Let's make a generic stack

playground

Generic Consequences

• Compiler generates three copies of the code for our example: one for each type at which it is instantiated

• Compiler can inline the code effectively, since it all has concrete types at compile time

• Generic types are still monomorphic: we can't mix types on our stack (but could use an enum type)

Turbofish

• Note that we changed the calling syntax in a funny way to fill in the types in our example

• An alternative is to fill in at the call site, but this requires special syntax

playground

Type Constraints

• There isn't much we can do with values of a generic type, since it's completely generic — any type could appear

• Can constrain generic types to obey particular "traits" (next lecture)

• This trades flexibility for usability; try to find the least constrained thing that will work

playground

• Where clauses are a thing