1 // Rust-101, Part 00: Algebraic datatypes
2 // ======================================
4 // As our first piece of Rust code, we want to write a function that computes the
8 // An `enum` for "a number or nothing" could look as follows:
14 // Observe how in Rust, the return type comes *after* the arguments.
15 fn vec_min(vec: Vec<i32>) -> NumberOrNothing {
16 let mut min = NumberOrNothing::Nothing;
18 // Now we want to *iterate* over the list. Rust has some nice syntax for iterators:
20 // So `el` is al element of the list. We need to update `min` accordingly, but how do we get the current
21 // number in there? This is what pattern matching can do:
23 // In this case (*arm*) of the `match`, `min` is currently nothing, so let's just make it the number `el`.
24 NumberOrNothing::Nothing => {
27 // In this arm, `min` is currently the number `n`, so let's compute the new minimum and store it.
28 NumberOrNothing::Number(n) => {
33 // Finally, we return the result of the computation.
37 // Now that we reduced the problem to computing the minimum of two integers, let's do that.
38 fn min_i32(a: i32, b: i32) -> i32 {
46 // Phew. We wrote our first Rust function! But all this `NumberOrNothing::` is getting kind of
47 // ugly. Can't we do that nicer?
49 // Indeed, we can: The following line tells Rust to take
50 // the constructors of `NumberOrNothing` into the local namespace.
51 // Try moving that above the function, and removing all the occurrences `NumberOrNothing::`.
52 use self::NumberOrNothing::{Number,Nothing};
54 // To call this function, we now just need a list. Of course, ultimately we want to ask the user for
55 // a list of numbers, but for now, let's just hard-code something.
57 fn read_vec() -> Vec<i32> {
61 // Of course, we would also like to actually see the result of the computation, so we need to print the result.
63 fn print_number_or_nothing(n: NumberOrNothing) {
67 // Putting it all together:
70 let min = vec_min(vec);
71 print_number_or_nothing(min);
74 // Finally, try `cargo run` on the console to run it.