finish part 2
[rust-101.git] / src / part02.rs
1 // Rust-101, Part 02: Generic types, Traits
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. So here, we define
14 // a generic type `SomethingOrNothing`.
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 // **Exercise**: Write functions converting between `SomethingOrNothing<T>` and `Option<T>`. You will have to use
29 // the names of the constructor of `Option`, which you can find in the documentation I linked above.
30 // 
31 // Here's a skeleton for your solution, you only have to fill in the function bodies.
32 // (`panic!` is, again, a macro - this one terminates execution when it is reached).
33 // 
34 // Notice the syntax for giving generic implementations to generic types: Think of the first `<T>` 
35 // as *declaring* a type variable ("I am doing something for all types `T`"), and the second `<T>` as
36 // *using* that variable ("The thing I do, is implement `SomethingOrNothing<T>`").
37 impl<T> SomethingOrNothing<T> {
38     fn new(o: Option<T>) -> Self {
39         panic!("Not yet implemented.")
40     }
41
42     fn to_option(self) -> Option<T> {
43         panic!("Not yet implemented.")
44     }
45 }
46 // Inside an `impl`, `Self` refers to the type we are implementing things for. Here, it is
47 // an alias for `SomethingOrNothing<T>`.
48 // Remember that `self` is the `this` of Rust, and implicitly has type `Self`.
49 // 
50 // Observe how `new` does *not* have a `self` parameter. This corresponds to a `static` method
51 // in Java or C++. In fact, `new` is the Rust convention for defining constructors: They are
52 // nothing special, just static functions returning `Self`.
53
54 // You can call static functions, and in particular constructors, as follows:
55 fn call_constructor(x: i32) -> SomethingOrNothing<i32> {
56     SomethingOrNothing::new(Some(x))
57 }
58
59 // Now that we have a generic `SomethingOrNothing`, wouldn't it be nice to also gave a generic
60 // `vec_min`? Of course, we can't take the minimum of a vector of *any* type. It has to be a type
61 // supporting a `min` operation. Rust calls such properties that we may demand of types *traits*.
62
63 // So, as a first step towards a generic `vec_min`, we define a `Minimum` trait.
64 // For now, just ignore the `Copy`, we will come back to this point later.
65 // A `trait` is a lot like interfaces in Java: You define a bunch of functions
66 // you want to have implemented, and their argument and return types.
67 trait Minimum : Copy {
68     fn min(a: Self, b: Self) -> Self;
69 }
70
71 // Now we can write `vec_min`, generic over a type `T` that we demand to satisfy the `Minimum` trait.
72 // This is called a *trait bound*.
73 // The only difference to the version from the previous part is that we call `T::min` (the `min`
74 // function provided for type `T`) instead of `std::cmp::min`.
75 // 
76 // Notice a crucial difference to templates in C++: We actually have to declare which traits
77 // we want the type to satisfy. If we left away the `Minimum`, Rust would have complained that
78 // we cannot call `min`. Just try it! There is no reason to believe that `T` provides such an operation.
79 // This is in strong contrast to C++, where the compiler only checks such details when the
80 // function is actually used.
81 fn vec_min<T: Minimum>(v: &Vec<T>) -> SomethingOrNothing<T> {
82     let mut min = Nothing;
83     for e in v {
84         let e = *e;
85         min = Something(match min {
86             Nothing => e,
87             Something(n) => T::min(n, e)
88         });
89     }
90     min
91 }
92
93 // To make the function usable with a `Vec<i32>`, we implement the `Minimum` trait for `i32`.
94 impl Minimum for i32 {
95     fn min(a: Self, b: Self) -> Self {
96         std::cmp::min(a, b)
97     }
98 }
99
100 // In order to run our code and see the result, we again provide a `print` function.
101 // This also shows that we can have multiple `impl` blocks for the same type, and we
102 // can provide some methods only for certain instances of a generic type.
103 impl SomethingOrNothing<i32> {
104     fn print(self) {
105         match self {
106             Nothing => println!("The number is: <nothing>"),
107             Something(n) => println!("The number is: {}", n),
108         };
109     }
110 }
111
112 // Now we are again ready to run our code. Remember to change `main.rs` appropriately.
113 // Rust figures out automatically that we want the `T` of `vec_min` to be `i32`, and
114 // that `i32` implements `Minimum` and hence all is good.
115 // 
116 // In case you are worried about performance, note that Rust performs *monomorphisation*
117 // of generic functions: When you call `vec_min` with `T` being `i32`, Rust essentially goes
118 // ahead and creates a copy of the function for this particular type, filling in all the blanks.
119 // In this case, the call to `T::min` will become a call to our implementation *statically*. There is
120 // no dynamic dispatch, like there would be for Java interface methods or C++ `virtual` methods.
121 // This behavior is similar to C++ templates. The optimizer (Rust is using LLVM) then has all the
122 // information it could want to, e.g., inline function calls.
123 fn read_vec() -> Vec<i32> {
124     vec![18,5,7,3,9,27]
125 }
126 pub fn part_main() {
127     let vec = read_vec();
128     let min = vec_min(&vec);
129     min.print();
130 }
131
132 // If this printed `3`, then you generic `vec_min` is working!
133 // 
134 // Before going on, take a moment to ponder the flexibility of Rust's take on abstraction:
135 // We just defined our own, custom trait (interface), and then implemented that trait
136 // *for an existing type*. With the hierarchical approach of, e.g., C++ or Java,
137 // that's not possible: We cannot make an existing type suddenly also inherit from our abstract base class.
138
139 // **Exercise**: Define a trait "Print" to write a generic version of `SomethingOrNothing::print`.
140 // Implement that trait for `i32`, and change the code above to use it.
141 // I will again provide a skeleton for this solution. It also shows how to attach bounds to generic
142 // implementations (just compare it to the `impl` block from the previous exercise).
143 // You can read this as "For all types `T` satisfying the `Print` trait, I provide an implementation
144 // for `SomethingOrNothing<T>`".
145 // 
146 // Notice that I called the function on `SomethingOrNothing` `print2` to disambiguate from the `print` defined above.
147 // 
148 // *Hint*: There is a macro `print!` for printing without appending a newline.
149 trait Print {
150     /* Add things here */
151 }
152 impl<T: Print> SomethingOrNothing<T> {
153     fn print2(self) {
154         panic!("Not yet implemented.")
155     }
156 }
157
158 // [index](main.html) | [previous](part01.html) | next