work on Intro; import code from previous parts where appropriate
[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 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 to define an entire family of types: We can now write
22 // `SomethingOrNothing<i32>` to get back our `NumberOrNothing`, but we
23 // can also write `SomethingOrNothing<bool>` or even `SomethingOrNothing<SomethingOrNothing<i32>>`.
24 // In fact, such a type is so useful that it is already present in the standard
25 // library: It's called an *option type*, written `Option<T>`.
26 // Go check out its [documentation](http://doc.rust-lang.org/stable/std/option/index.html)!
27 // (And don't worry, there's indeed lots of material mentioned there that we did not cover yet.)
28
29 // **Exercise**: Write functions converting between `SomethingOrNothing<T>` and `Option<T>`. You will have to use
30 // the names of the constructor of `Option`, which you can find in the documentation I linked above.
31 // 
32 // Here's a skeleton for your solution, you only have to fill in the function bodies.
33 // (`panic!` is, again, a macro - this one terminates execution when it is reached).
34 // 
35 // Notice the syntax for giving generic implementations to generic types: Think of the first `<T>` 
36 // as *declaring* a type variable ("I am doing something for all types `T`"), and the second `<T>` as
37 // *using* that variable ("The thing I do, is implement `SomethingOrNothing<T>`").
38 impl<T> SomethingOrNothing<T> {
39     fn new(o: Option<T>) -> Self {
40         panic!("Not yet implemented.")
41     }
42
43     fn to_option(self) -> Option<T> {
44         panic!("Not yet implemented.")
45     }
46 }
47 // Inside an `impl`, `Self` refers to the type we are implementing things for. Here, it is
48 // an alias for `SomethingOrNothing<T>`.
49 // Remember that `self` is the `this` of Rust, and implicitly has type `Self`.
50 // 
51 // Observe how `new` does *not* have a `self` parameter. This corresponds to a `static` method
52 // in Java or C++. In fact, `new` is the Rust convention for defining constructors: They are
53 // nothing special, just static functions returning `Self`.
54
55 // You can call static functions, and in particular constructors, as follows:
56 fn call_constructor(x: i32) -> SomethingOrNothing<i32> {
57     SomethingOrNothing::new(Some(x))
58 }
59
60 // Now that we have a generic `SomethingOrNothing`, wouldn't it be nice to also gave a generic
61 // `vec_min`? Of course, we can't take the minimum of a vector of *any* type. It has to be a type
62 // supporting a `min` operation. Rust calls such properties that we may demand of types *traits*.
63
64 // So, as a first step towards a generic `vec_min`, we define a `Minimum` trait.
65 // For now, just ignore the `Copy`, we will come back to this point later.
66 // A `trait` is a lot like interfaces in Java: You define a bunch of functions
67 // you want to have implemented, and their argument and return types.
68 pub trait Minimum : Copy {
69     fn min(a: Self, b: Self) -> Self;
70 }
71
72 // Now we can write `vec_min`, generic over a type `T` that we demand to satisfy the `Minimum` trait.
73 // This is called a *trait bound*.
74 // The only difference to the version from the previous part is that we call `T::min` (the `min`
75 // function provided for type `T`) instead of `std::cmp::min`.
76 // 
77 // Notice a crucial difference to templates in C++: We actually have to declare which traits
78 // we want the type to satisfy. If we left away the `Minimum`, Rust would have complained that
79 // we cannot call `min`. Just try it! There is no reason to believe that `T` provides such an operation.
80 // This is in strong contrast to C++, where the compiler only checks such details when the
81 // function is actually used.
82 pub fn vec_min<T: Minimum>(v: Vec<T>) -> SomethingOrNothing<T> {
83     let mut min = Nothing;
84     for e in v {
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     pub 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 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](part03.html)