1 // Rust-101, Part 01: Expressions, Inherent methods
2 // ================================================
6 // Even though our code from the first part works, we can still learn a
7 // lot by making it prettier. To understand how, it is important to
8 // understand that Rust is an "expression-based" language. This means that most of the
9 // terms you write down are not just *statements* (executing code), but *expressions*
10 // (returning a value). This applies even to the body of entire functions!
12 // For example, consider `sqr`:
13 fn sqr(i: i32) -> i32 { i * i }
14 // Between the curly braces, we are giving the *expression* that computes the return value.
15 // So we can just write `i * i`, the expression that returns the square if `i`!
16 // This is very close to how mathematicians write down functions (but with more types).
18 // Conditionals are also just expressions. You can compare this to the ternary `? :` operator
19 // from languages like C.
20 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
22 // And the same applies to case distinction with `match`: Every `arm` of the match
23 // gives the expression that is returned in the respective case.
24 // (We repeat the definition from the previous part here.)
25 enum NumberOrNothing {
29 use self::NumberOrNothing::{Number,Nothing};
30 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
37 // With this fresh knowledge, let us now refactor `vec_min`. First of all, we are doing a small change
38 // to the type: `&Vec<i32>` denotes a *reference* to a `Vec<i32>`. You can think of this as a pointer
39 // (in C terms): Arguments in Rust are passed *by value*, so we need to employ explicit references if
40 // that's not what we want. References are per default immutable (like variables), a mutable reference
41 // would be denoted `&mut Vec<i32>`.
42 fn vec_min(v: &Vec<i32>) -> NumberOrNothing {
43 let mut min = Nothing;
45 // Now that `v` is just a reference, the same goes for `e`, so we have to dereference the pointer.
47 // Notice that all we do here is compute a new value for `min`, and that it will always end
48 // up being a `Number` rather than `Nothing`. In Rust, the structure of the code
49 // can express this uniformity.
50 min = Number(match min {
52 Number(n) => std::cmp::min(n, e)
55 // The `return` keyword exists in Rust, but it is rarely used. Instead, we typically
56 // make use of the fact that the entire function body is an expression, so we can just
57 // write down the desired return value.
61 // Now that's already much shorter! Make sure you can go over the code above and actually understand
62 // every step of what's going on.
64 // So much for `vec_min`. Let us now reconsider `print_number_or_nothing`. That function
65 // really belongs pretty close to the type `NumberOrNothing`. In C++ or Java, you would
66 // probably make it a method of the type. In Rust, we can achieve something very similar
67 // by providing an *inherent implementation*.
68 impl NumberOrNothing {
71 Nothing => println!("The number is: <nothing>"),
72 Number(n) => println!("The number is: {}", n),
76 // So, what just happened? Rust separates code from data, so the definition of the
77 // methods on an `enum` (and also on `struct`, which we will learn about later)
78 // is independent of the definition of the type. `self` is like `this` in other
79 // languages, and its type is always implicit. So `print` is now a method that
80 // takes as first argument a `NumberOrNothing`, just like `print_number_or_nothing`.
82 // Try making `number_or_default` from above an inherent method as well!
84 // With our refactored functions and methods, `main` now looks as follows:
85 fn read_vec() -> Vec<i32> {
90 let min = vec_min(&vec);
93 // You will have to replace `part00` by `part01` in the `main` function in
94 // `main.rs` to run this code.
96 // **Exercise**: Write a funtion `vec_avg` that computes the average value of a `Vec<i32>`.
98 // *Hint*: `vec.len()` returns the length of a vector `vec`.
100 // [index](main.html) | [previous](part00.html) | [next](part02.html)