1 // Rust-101, Part 01: Expressions, Inherent methods
2 // ================================================
4 // For Rust to compile this file, make sure to enable the corresponding line
5 // in `main.rs` before going on.
8 // ## Expression-based programming
9 fn sqr(i: i32) -> i32 { i * i }
11 // Conditionals are also just expressions. This is comparable to the ternary `? :` operator
12 // from languages like C.
13 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
15 enum NumberOrNothing {
19 use self::NumberOrNothing::{Number,Nothing};
20 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
27 // It is even the case that blocks are expressions, evaluating to the last expression they contain.
28 fn compute_stuff(x: i32) -> i32 {
29 let y = { let z = x*x; z + 14 };
33 // Let us now refactor `vec_min`.
34 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
35 fn min_i32(a: i32, b: i32) -> i32 {
39 let mut min = Nothing;
46 // Now that's already much shorter! Make sure you can go over the code above and actually understand
47 // every step of what's going on.
49 // ## Inherent implementations
50 impl NumberOrNothing {
53 Nothing => println!("The number is: <nothing>"),
54 Number(n) => println!("The number is: {}", n),
59 // With our refactored functions and methods, `main` now looks as follows:
60 fn read_vec() -> Vec<i32> {
65 let min = vec_min(vec);
68 // You will have to replace `part00` by `part01` in the `main` function in
69 // `main.rs` to run this code.
71 // **Exercise 01.1**: Write a function `vec_sum` that computes the sum of all values of a `Vec<i32>`.
73 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.