1 // ***Remember to enable/add this part in `main.rs`!***
3 // Rust-101, Part 02: Generic types, Traits
4 // ========================================
7 // ## Generic datatypes
9 pub enum SomethingOrNothing<T> {
13 // Instead of writing out all the variants, we can also just import them all at once.
14 pub use self::SomethingOrNothing::*;
15 type NumberOrNothing = SomethingOrNothing<i32>;
17 // ## Generic `impl`, Static functions
18 // Inside an `impl`, `Self` refers to the type we are implementing things for. Here, it is
19 // an alias for `SomethingOrNothing<T>`.
20 impl<T> SomethingOrNothing<T> {
21 fn new(o: Option<T>) -> Self {
25 fn to_option(self) -> Option<T> {
29 // You can call static functions, and in particular constructors, as demonstrated in `call_constructor`.
30 fn call_constructor(x: i32) -> SomethingOrNothing<i32> {
31 SomethingOrNothing::new(Some(x))
36 pub trait Minimum : Copy {
37 fn min(self, b: Self) -> Self;
40 pub fn vec_min<T: Minimum>(v: Vec<T>) -> SomethingOrNothing<T> {
41 let mut min = Nothing;
43 min = Something(match min {
45 // Here, we can now call the `min` function of the trait.
54 // ## Trait implementations
55 // To make `vec_min` usable with a `Vec<i32>`, we implement the `Minimum` trait for `i32`.
56 impl Minimum for i32 {
57 fn min(self, b: Self) -> Self {
62 // We again provide a `print` function.
63 impl NumberOrNothing {
66 Nothing => println!("The number is: <nothing>"),
67 Something(n) => println!("The number is: {}", n),
72 // Now we are ready to run our new code. Remember to change `main.rs` appropriately.
73 fn read_vec() -> Vec<i32> {
78 let min = vec_min(vec);
83 // **Exercise 02.1**: Change your program such that it computes the minimum of a `Vec<f32>` (where `f32` is the type
84 // of 32-bit floating-point numbers). You should not change `vec_min` in any way, obviously!