tuning
[rust-101.git] / workspace / src / part03.rs
1 // ***Remember to enable/add this part in `main.rs`!***
2
3 // Rust-101, Part 03: Input
4 // ========================
5
6
7 // I/O is provided by the module `std::io`, so we first have import that with `use`.
8 // We also import the I/O *prelude*, which makes a bunch of commonly used I/O stuff
9 // directly available.
10 use std::io::prelude::*;
11 use std::io;
12
13 fn read_vec() -> Vec<i32> {
14     let mut vec: Vec<i32> = Vec::<i32>::new();
15     // The central handle to the standard input is made available by `io::stdin()`.
16     let stdin = io::stdin();
17     println!("Enter a list of numbers, one per line. End with Ctrl-D.");
18     for line in stdin.lock().lines() {
19         // Rust's type for (dynamic, growable) strings is `String`. However, our variable `line`
20         // here is not yet of that type: It has type `io::Result<String>`.
21
22         // I chose the same name (`line`) for the new variable to ensure that I will never, accidentally,
23         // access the "old" `line` again.
24         let line = line.unwrap();
25         // Now that we have our `String`, we want to make it an `i32`.
26
27         match line.parse::<i32>() {
28             Ok(num) => {
29                 unimplemented!()
30             },
31             // We don't care about the particular error, so we ignore it with a `_`.
32             Err(_) => {
33                 unimplemented!()
34             },
35         }
36     }
37
38     vec
39 }
40
41
42 // For the rest of the code, we just re-use part 02 by importing it with `use`.
43 use part02::{SomethingOrNothing,Something,Nothing,vec_min};
44
45 // If you update your `main.rs` to use part 03, `cargo run` should now ask you for some numbers,
46 // and tell you the minimum. Neat, isn't it?
47 pub fn main() {
48     let vec = read_vec();
49     unimplemented!()
50 }
51
52 // **Exercise 03.1**: Define a trait `Print` to write a generic version of `SomethingOrNothing::print`.
53 // Implement that trait for `i32`, and change the code above to use it.
54 // I will again provide a skeleton for this solution. It also shows how to attach bounds to generic
55 // implementations (just compare it to the `impl` block from the previous exercise).
56 // You can read this as "For all types `T` satisfying the `Print` trait, I provide an implementation
57 // for `SomethingOrNothing<T>`".
58 // 
59 // Notice that I called the function on `SomethingOrNothing` `print2` to disambiguate from the `print` defined previously.
60 // 
61 // *Hint*: There is a macro `print!` for printing without appending a newline.
62 trait Print {
63     /* Add things here */
64 }
65 impl<T: Print> SomethingOrNothing<T> {
66     fn print2(self) {
67         unimplemented!()
68     }
69 }
70
71 // **Exercise 03.2**: Building on exercise 02.2, implement all the things you need on `f32` to make your
72 // program work with floating-point numbers.
73