1 // Rust-101, Part 02: Generic types, Traits
2 // ========================================
5 // ## Generic datatypes
7 pub enum SomethingOrNothing<T> {
11 // Instead of writing out all the variants, we can also just import them all at once.
12 pub use self::SomethingOrNothing::*;
13 type NumberOrNothing = SomethingOrNothing<i32>;
15 // ## Generic `impl`, Static functions
16 // Inside an `impl`, `Self` refers to the type we are implementing things for. Here, it is
17 // an alias for `SomethingOrNothing<T>`.
18 impl<T> SomethingOrNothing<T> {
19 fn new(o: Option<T>) -> Self {
23 fn to_option(self) -> Option<T> {
27 // You can call static functions, and in particular constructors, as demonstrated in `call_constructor`.
28 fn call_constructor(x: i32) -> SomethingOrNothing<i32> {
29 SomethingOrNothing::new(Some(x))
34 pub trait Minimum : Copy {
35 fn min(self, b: Self) -> Self;
38 pub fn vec_min<T: Minimum>(v: Vec<T>) -> SomethingOrNothing<T> {
39 let mut min = Nothing;
41 min = Something(match min {
43 // Here, we can now call the `min` function of the trait.
52 // ## Trait implementations
53 // To make `vec_min` usable with a `Vec<i32>`, we implement the `Minimum` trait for `i32`.
54 impl Minimum for i32 {
55 fn min(self, b: Self) -> Self {
60 // We again provide a `print` function.
61 impl NumberOrNothing {
64 Nothing => println!("The number is: <nothing>"),
65 Something(n) => println!("The number is: {}", n),
70 // Now we are ready to run our new code. Remember to change `main.rs` appropriately.
71 fn read_vec() -> Vec<i32> {
76 let min = vec_min(vec);
81 // **Exercise 02.1**: Change your program such that it computes the minimum of a `Vec<f32>` (where `f32` is the type
82 // of 32-bit floating-point numbers). You should not change `vec_min` in any way, obviously!