1 // Rust-101, Part 01: Expressions, Inherent methods
2 // ================================================
4 // Even though our code from the first part works, we can still learn a
5 // lot by making it prettier. To understand how, it is important to
6 // understand that Rust is an "expression-based" language. This means that most of the
7 // terms you write down are not just *statements* (executing code), but *expressions*
8 // (returning a value). This applies even to the body of entire functions!
10 // ## Expression-based programming
11 // For example, consider `sqr`:
12 fn sqr(i: i32) -> i32 { i * i }
13 // Between the curly braces, we are giving the *expression* that computes the return value.
14 // So we can just write `i * i`, the expression that returns the square if `i`!
15 // This is very close to how mathematicians write down functions (but with more types).
17 // Conditionals are also just expressions. You can compare this to the ternary `? :` operator
18 // from languages like C.
19 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
21 // And the same applies to case distinction with `match`: Every `arm` of the match
22 // gives the expression that is returned in the respective case.
23 // (We repeat the definition from the previous part here.)
24 enum NumberOrNothing {
28 use self::NumberOrNothing::{Number,Nothing};
29 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
36 // Let us now refactor `vec_min`.
37 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
38 // Remember that helper function `min_i32`? Rust allows us to define such helper functions *inside* other
39 // functions. This is just a matter of namespacing, the inner function has no access to the data of the outer
40 // one. Still, being able to nicely group functions can be very useful.
41 fn min_i32(a: i32, b: i32) -> i32 {
42 if a < b { a } else { b }
45 let mut min = Nothing;
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) => min_i32(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 // ## Inherent implementations
65 // So much for `vec_min`. Let us now reconsider `print_number_or_nothing`. That function
66 // really belongs pretty close to the type `NumberOrNothing`. In C++ or Java, you would
67 // probably make it a method of the type. In Rust, we can achieve something very similar
68 // by providing an *inherent implementation*.
69 impl NumberOrNothing {
72 Nothing => println!("The number is: <nothing>"),
73 Number(n) => println!("The number is: {}", n),
77 // So, what just happened? Rust separates code from data, so the definition of the
78 // methods on an `enum` (and also on `struct`, which we will learn about later)
79 // is independent of the definition of the type. `self` is like `this` in other
80 // languages, and its type is always implicit. So `print` is now a method that
81 // takes as first argument a `NumberOrNothing`, just like `print_number_or_nothing`.
83 // Try making `number_or_default` from above an inherent method as well!
85 // With our refactored functions and methods, `main` now looks as follows:
86 fn read_vec() -> Vec<i32> {
91 let min = vec_min(vec);
94 // You will have to replace `part00` by `part01` in the `main` function in
95 // `main.rs` to run this code.
97 // **Exercise 01.1**: Write a funtion `vec_sum` that computes the sum of all values of a `Vec<i32>`.
99 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.
101 // [index](main.html) | [previous](part00.html) | [next](part02.html)