1 // ***Remember to enable/add this part in `main.rs`!***
3 // Rust-101, Part 01: Expressions, Inherent methods
4 // ================================================
6 // For Rust to compile this file, make sure to enable the corresponding line
7 // in `main.rs` before going on.
10 // ## Expression-based programming
11 fn sqr(i: i32) -> i32 { i * i }
13 // Conditionals are also just expressions. You can compare this to the ternary `? :` operator
14 // from languages like C.
15 fn abs(i: i32) -> i32 { if i >= 0 { i } else { -i } }
17 enum NumberOrNothing {
21 use self::NumberOrNothing::{Number,Nothing};
22 fn number_or_default(n: NumberOrNothing, default: i32) -> i32 {
29 // Let us now refactor `vec_min`.
30 fn vec_min(v: Vec<i32>) -> NumberOrNothing {
31 fn min_i32(a: i32, b: i32) -> i32 {
35 let mut min = Nothing;
42 // Now that's already much shorter! Make sure you can go over the code above and actually understand
43 // every step of what's going on.
45 // ## Inherent implementations
46 impl NumberOrNothing {
49 Nothing => println!("The number is: <nothing>"),
50 Number(n) => println!("The number is: {}", n),
55 // With our refactored functions and methods, `main` now looks as follows:
56 fn read_vec() -> Vec<i32> {
61 let min = vec_min(vec);
64 // You will have to replace `part00` by `part01` in the `main` function in
65 // `main.rs` to run this code.
67 // **Exercise 01.1**: Write a funtion `vec_sum` that computes the sum of all values of a `Vec<i32>`.
69 // **Exercise 01.2**: Write a function `vec_print` that takes a vector and prints all its elements.