1 // ***Remember to enable/add this part in `main.rs`!***
3 // Rust-101, Part 00: Algebraic datatypes
4 // ======================================
6 // As our first piece of Rust code, we want to write a function that computes the
10 // An `enum` for "a number or nothing" could look as follows:
11 enum NumberOrNothing {
16 // Observe how in Rust, the return type comes *after* the arguments.
17 fn vec_min(vec: Vec<i32>) -> NumberOrNothing {
18 let mut min = NumberOrNothing::Nothing;
20 // Now we want to *iterate* over the list. Rust has some nice syntax for
23 // So `el` is al element of the list. We need to update `min` accordingly, but how do we get the current
24 // number in there? This is what pattern matching can do:
26 // In this case (*arm*) of the `match`, `min` is currently nothing, so let's just make it the number `el`.
27 NumberOrNothing::Nothing => {
30 // In this arm, `min` is currently the number `n`, so let's compute the new minimum and store it.
31 NumberOrNothing::Number(n) => {
36 // Finally, we return the result of the computation.
40 // Now that we reduced the problem to computing the minimum of two integers, let's do that.
41 fn min_i32(a: i32, b: i32) -> i32 {
49 // Phew. We wrote our first Rust function! But all this `NumberOrNothing::` is getting kind of
50 // ugly. Can't we do that nicer?
52 // Indeed, we can: The following line tells Rust to take
53 // the constructors of `NumberOrNothing` into the local namespace.
54 // Try moving that above the function, and removing all the occurrences `NumberOrNothing::`.
55 use self::NumberOrNothing::{Number,Nothing};
57 // To call this function, we now just need a list. Of course, ultimately we want to ask the user for
58 // a list of numbers, but for now, let's just hard-code something.
60 fn read_vec() -> Vec<i32> {
64 // Finally, let's call our functions and run the code!
65 // But, wait, we would like to actually see something, so we need to print the result.
66 // Of course Rust can print numbers, but after calling `vec_min`, we have a `NumberOrNothing`.
67 // So let's write a small helper function that prints such values.
69 fn print_number_or_nothing(n: NumberOrNothing) {
73 // Putting it all together:
76 let min = vec_min(vec);
77 print_number_or_nothing(min);
80 // You can now use `cargo build` to compile your code. If all goes well, try `cargo run` on the