Merge pull request #42 from zdyxry/master
[rust-101.git] / src / part01.rs
1 // Rust-101, Part 01: Expressions, Inherent methods
2 // ================================================
3
4 // For Rust to compile this file, make sure to enable the corresponding line
5 // in `main.rs` before going on.
6
7 //@ Even though our code from the first part works, we can still learn a
8 //@ lot by making it prettier. That's because Rust is an "expression-based" language, which
9 //@ means that most of the terms you write down are not just *statements* (executing code), but
10 //@ *expressions* (returning a value). This applies even to the body of entire functions!
11
12 // ## Expression-based programming
13 //@ For example, consider `sqr`:
14 fn sqr(i: i32) -> i32 { i * i }
15 //@ Between the curly braces, we are giving the *expression* that computes the return value.
16 //@ So we can just write `i * i`, the expression that returns the square of `i`!
17 //@ This is very close to how mathematicians write down functions (but with more types).
18
19 // Conditionals are also just expressions. This is comparable to the ternary `? :` operator
20 // from languages like C.
21 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
22
23 //@ And the same applies to case distinction with `match`: Every `arm` of the match
24 //@ gives the expression that is returned in the respective case.
25 //@ (We repeat the definition from the previous part here.)
26 enum NumberOrNothing {
27     Number(i32),
28     Nothing
29 }
30 use self::NumberOrNothing::{Number,Nothing};
31 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
32     match n {
33         Nothing => default,
34         Number(n) => n,
35     }
36 }
37
38 // It is even the case that blocks are expressions, evaluating to the last expression they contain.
39 fn compute_stuff(x: i32) -> i32 {
40     let y = { let z = x*x; z + 14 };
41     y*y
42 }
43
44 // Let us now refactor `vec_min`.
45 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
46     //@ Remember that helper function `min_i32`? Rust allows us to define such helper functions
47     //@ *inside* other functions. This is just a matter of namespacing, the inner function has no
48     //@ access to the data of the outer one. Still, being able to nicely group functions can
49     //@ significantly increase readability.
50     fn min_i32(a: i32, b: i32) -> i32 {
51         if a < b { a } else { b }                                   /*@*/
52     }
53
54     let mut min = Nothing;
55     for e in v {
56         //@ Notice that all we do here is compute a new value for `min`, and that it will always end
57         //@ up being a `Number` rather than `Nothing`. In Rust, the structure of the code
58         //@ can express this uniformity.
59         min = Number(match min {                                    /*@*/
60             Nothing => e,                                           /*@*/
61             Number(n) => min_i32(n, e)                              /*@*/
62         });                                                         /*@*/
63     }
64     //@ The `return` keyword exists in Rust, but it is rarely used. Instead, we typically
65     //@ make use of the fact that the entire function body is an expression, so we can just
66     //@ write down the desired return value.
67     min
68 }
69
70 // Now that's already much shorter! Make sure you can go over the code above and actually understand
71 // every step of what's going on.
72
73 // ## Inherent implementations
74 //@ So much for `vec_min`. Let us now reconsider `print_number_or_nothing`. That function
75 //@ really belongs pretty close to the type `NumberOrNothing`. In C++ or Java, you would
76 //@ probably make it a method of the type. In Rust, we can achieve something very similar
77 //@ by providing an *inherent implementation*.
78 impl NumberOrNothing {
79     fn print(self) {
80         match self {
81             Nothing => println!("The number is: <nothing>"),
82             Number(n) => println!("The number is: {}", n),
83         };
84     }
85 }
86 //@ So, what just happened? Rust separates code from data, so the definition of the
87 //@ methods on an `enum` (and also on `struct`, which we will learn about later)
88 //@ is independent of the definition of the type. `self` is like `this` in other
89 //@ languages, and its type is always implicit. So `print` is now a method that
90 //@ takes `NumberOrNothing` as the first argument, just like `print_number_or_nothing`.
91 //@ 
92 //@ Try making `number_or_default` from above an inherent method as well!
93
94 // With our refactored functions and methods, `main` now looks as follows:
95 fn read_vec() -> Vec<i32> {
96     vec![18,5,7,2,9,27]
97 }
98 pub fn main() {
99     let vec = read_vec();
100     let min = vec_min(vec);
101     min.print();                                                    /*@*/
102 }
103 // You will have to replace `part00` by `part01` in the `main` function in
104 // `main.rs` to run this code.
105
106 // **Exercise 01.1**: Write a function `vec_sum` that computes the sum of all values of a `Vec<i32>`.
107
108 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.
109
110 //@ [index](main.html) | [previous](part00.html) | [raw source](workspace/src/part01.rs) |
111 //@ [next](part02.html)