Git repo: https://github.com/caveofprogramming/rust
Generics allow us to create structs, enums or functions that can work with types of things that are inferred, apparently at compile time.
Rust implements them by just compiling different versions of your struct or function, to work with the required types.
Generic Structs
Here is a struct with two fields of some unspecified generic type.
When we actually create a struct, Rust can infer the type T.
Here I’ve now got a struct with two i32 fields, but we could also create a Point struct that has floating point fields or strings or whatever.
We can implement functions on the struct that only work with specified types. The following implementation will only work if my Point struct has i32 fields.
We can also create generic implementations that will then work with Point structs of any type, but in that case we’re quite limited in what we can do with the fields, since we don’t know their types.
This limitation can be overcome by using traits, which we’ll look at next time.
The following implementation just allows us to access the value of the x field via a function x()
Generic Functions
If I try to compile the following function I’ll get an error, because we don’t know whether x and y can actually be added together or not.
The error text suggests I add some trait information.
Now we can use the function and it works.
Explicitly Declaring Generic Types
This is something I discovered via some browsing and experimentation. If we want to explicitly declare the generic type, we can do so using :: . Not sure what implications this has, but hopefully we’ll find out later on.