part02.rs lines shortened
[rust-101.git] / src / part02.rs
1 // Rust-101, Part 02: Generic types, Traits
2 // ========================================
3
4 //@ Let us for a moment reconsider the type `NumberOrNothing`. Isn't it a bit annoying that we
5 //@ had to hard-code the type `i32` in there? What if tomorrow, we want a `CharOrNothing`, and
6 //@ later a `FloatOrNothing`? Certainly we don't want to re-write the type and all its inherent
7 //@ methods.
8
9 // ## Generic datatypes
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. So here, we define
14 //@ a generic type `SomethingOrNothing`.
15 pub enum SomethingOrNothing<T>  {
16     Something(T),
17     Nothing,
18 }
19 // Instead of writing out all the variants, we can also just import them all at once.
20 pub use self::SomethingOrNothing::*;
21 //@ What this does is define an entire family of types: We can now write
22 //@ `SomethingOrNothing<i32>` to get back our `NumberOrNothing`.
23 type NumberOrNothing = SomethingOrNothing<i32>;
24
25 //@ However, we can also write `SomethingOrNothing<bool>` or even
26 //@ `SomethingOrNothing<SomethingOrNothing<i32>>`. In fact, a type like `SomethingOrNothing` is so
27 //@ useful that it is already present in the standard library: It's called an *option type*,
28 //@ written `Option<T>`. Go check out its
29 //@ [documentation](https://doc.rust-lang.org/stable/std/option/index.html)! (And don't worry,
30 //@ there's indeed lots of material mentioned there that we have not covered yet.)
31
32 // ## Generic `impl`, Static functions
33 //@ The types are so similar, that we can provide a generic function to construct a
34 //@ `SomethingOrNothing<T>` from an `Option<T>`, and vice versa.
35 //@ 
36 //@ Notice the syntax for giving generic implementations to generic types: Think of the first `<T>` 
37 //@ as *declaring* a type variable ("I am doing something for all types `T`"), and the second `<T>`
38 //@ as *using* that variable ("The thing I do, is implement `SomethingOrNothing<T>`").
39 //@
40 // Inside an `impl`, `Self` refers to the type we are implementing things for. Here, it is
41 // an alias for `SomethingOrNothing<T>`.
42 //@ Remember that `self` is the `this` of Rust, and implicitly has type `Self`.
43 impl<T> SomethingOrNothing<T> {
44     fn new(o: Option<T>) -> Self {
45         match o { None => Nothing, Some(t) => Something(t) }        /*@*/
46     }
47
48     fn to_option(self) -> Option<T> {
49         match self { Nothing => None, Something(t) => Some(t) }     /*@*/
50     }
51 }
52 //@ Observe how `new` does *not* have a `self` parameter. This corresponds to a `static` method
53 //@ in Java or C++. In fact, `new` is the Rust convention for defining constructors: They are
54 //@ nothing special, just static functions returning `Self`.
55 //@ 
56 // You can call static functions, and in particular constructors, as demonstrated in `call_constructor`.
57 fn call_constructor(x: i32) -> SomethingOrNothing<i32> {
58     SomethingOrNothing::new(Some(x))
59 }
60
61 // ## Traits
62 //@ Now that we have a generic `SomethingOrNothing`, wouldn't it be nice to also have a generic
63 //@ `vec_min`? Of course, we can't take the minimum of a vector of *any* type. It has to be a type
64 //@ supporting a `min` operation. Rust calls such properties that we may demand of types *traits*.
65
66 //@ So, as a first step towards a generic `vec_min`, we define a `Minimum` trait.
67 //@ For now, just ignore the `Copy`, we will come back to this point later.
68 //@ A `trait` is a lot like interfaces in Java: You define a bunch of functions
69 //@ you want to have implemented, and their argument and return types. <br/>
70 //@ The function `min` takes two arguments of the same type, but I made the
71 //@ first argument the special `self` argument. I could, alternatively, have
72 //@ made `min` a static function as follows: `fn min(a: Self, b: Self) -> Self`.
73 //@ However, in Rust one typically prefers methods over static functions wherever possible.
74 pub trait Minimum : Copy {
75     fn min(self, b: Self) -> Self;
76 }
77
78 //@ Next, we write `vec_min` as a generic function over a type `T` that we demand to satisfy the `Minimum` trait.
79 //@ This requirement is called a *trait bound*.
80 //@ The only difference to the version from the previous part is that we call `e.min(n)` instead
81 //@ of `std::cmp::min(n, e)`. Rust automatically figures out that `n` is of type `T`, which implements
82 //@ the `Minimum` trait, and hence we can call that function.
83 //@ 
84 //@ There is a crucial difference to templates in C++: We actually have to declare which traits
85 //@ we want the type to satisfy. If we left away the `Minimum`, Rust would have complained that
86 //@ we cannot call `min`. Just try it! <br/>
87 //@ This is in strong contrast to C++, where the compiler only checks such details when the
88 //@ function is actually used.
89 pub fn vec_min<T: Minimum>(v: Vec<T>) -> SomethingOrNothing<T> {
90     let mut min = Nothing;
91     for e in v {
92         min = Something(match min {
93             Nothing => e,
94             // Here, we can now call the `min` function of the trait.
95             Something(n) => {
96                 e.min(n)                                            /*@*/
97             }
98         });
99     }
100     min
101 }
102 //@ Before going on, take a moment to ponder the flexibility of Rust's take on abstraction:
103 //@ We just defined our own, custom trait (interface), and then implemented that trait
104 //@ *for an existing type*. With the hierarchical approach of, e.g., C++ or Java,
105 //@ that's not possible: We cannot make an existing type also inherit from our abstract base class
106 //@ after the fact.
107 //@ 
108 //@ In case you are worried about performance, note that Rust performs *monomorphisation*
109 //@ of generic functions: When you call `vec_min` with `T` being `i32`, Rust essentially goes
110 //@ ahead and creates a copy of the function for this particular type, filling in all the blanks.
111 //@ In this case, the call to `T::min` will become a call to our implementation *statically*. There
112 //@ is no dynamic dispatch, like there would be for Java interface methods or C++ `virtual` methods.
113 //@ This behavior is similar to C++ templates. The optimizer (Rust is using LLVM) then has all the
114 //@ information it could want to, e.g., inline function calls.
115
116 // ## Trait implementations
117 // To make `vec_min` usable with a `Vec<i32>`, we implement the `Minimum` trait for `i32`.
118 impl Minimum for i32 {
119     fn min(self, b: Self) -> Self {
120         if self < b { self } else { b }                             /*@*/
121     }
122 }
123
124 // We again provide a `print` function.
125
126
127 //@ This also shows that we can have multiple `impl` blocks for the same type (remember that
128 //@ `NumberOrNothing` is just a type alias for `SomethingOrNothing<i32>`), and we can provide some
129 //@ methods only for certain instances of a generic type.
130 impl NumberOrNothing {
131     pub fn print(self) {
132         match self {
133             Nothing => println!("The number is: <nothing>"),
134             Something(n) => println!("The number is: {}", n),
135         };
136     }
137 }
138
139 // Now we are ready to run our new code. Remember to change `main.rs` appropriately.
140 //@ Rust figures out automatically that we want the `T` of `vec_min` to be `i32`, and
141 //@ that `i32` implements `Minimum` and hence all is good.
142 fn read_vec() -> Vec<i32> {
143     vec![18,5,7,3,9,27]
144 }
145 pub fn main() {
146     let vec = read_vec();
147     let min = vec_min(vec);
148     min.print();
149 }
150
151 //@ If this printed `3`, then your generic `vec_min` is working! So get ready for the next part.
152
153 // **Exercise 02.1**: Change your program such that it computes the minimum of a `Vec<f32>` (where
154 // `f32` is the type // of 32-bit floating-point numbers). You should not change `vec_min` in any
155 // way, obviously!
156
157 //@ [index](main.html) | [previous](part01.html) | [raw source](workspace/src/part02.rs) |
158 //@ [next](part03.html)