start in part 02
[rust-101.git] / src / part02.rs
1 // Rust-101, Part 02: Generic types (WIP)
2 // ================================
3
4 use std;
5
6 // Let us for a moment reconsider the type `NumberOrNothing`. Isn't it a bit
7 // annoying that we had to hard-code the type `i32` in there? What if tomorrow,
8 // we want a `CharOrNothing`, and later a `FloatOrNothing`? Certainly we don't
9 // want to re-write the type and all its inherent methods.
10 // 
11 // The solution to this is called *generics* or *polymorphism* (the latter is Greek,
12 // meaning "many shapes"). You may know something similar from C++ (where it's called
13 // *templates*) or Java, or one of the many functional languages. A generic
14 // `SomethingOrNothing` type looks as follows:
15 enum SomethingOrNothing<T>  {
16     Something(T),
17     Nothing,
18 }
19 use self::SomethingOrNothing::{Something,Nothing};
20 // What this does is to define an entire family of types: We can now write
21 // `SomethingOrNothing<i32>` to get back our `NumberOrNothing`, but we
22 // can also write `SomethingOrNothing<bool>` or even `SomethingOrNothing<SomethingOrNothing<i32>>`.
23 // In fact, such a type is so useful that it is already present in the standard
24 // library: It's called an *option type*, written `Option<T>`.
25 // Go check out its [documentation](http://doc.rust-lang.org/stable/std/option/index.html)!
26 // (And don't worry, there's indeed lots of material mentioned there that we did not cover yet.)
27
28 // [index](main.html) | [previous](part01.html) | [next](part03.html)