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. You can compare this 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 // Let us now refactor `vec_min`.
28 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
29 fn min_i32(a: i32, b: i32) -> i32 {
33 let mut min = Nothing;
40 // Now that's already much shorter! Make sure you can go over the code above and actually understand
41 // every step of what's going on.
43 // ## Inherent implementations
44 impl NumberOrNothing {
47 Nothing => println!("The number is: <nothing>"),
48 Number(n) => println!("The number is: {}", n),
53 // With our refactored functions and methods, `main` now looks as follows:
54 fn read_vec() -> Vec<i32> {
59 let min = vec_min(vec);
62 // You will have to replace `part00` by `part01` in the `main` function in
63 // `main.rs` to run this code.
65 // **Exercise 01.1**: Write a funtion `vec_sum` that computes the sum of all values of a `Vec<i32>`.
67 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.