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