1 // ***Remember to enable/add this part in `main.rs`!***
3 // Rust-101, Part 03: Input
4 // ========================
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
10 use std::io::prelude::*;
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>`.
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`.
27 match line.parse::<i32>() {
31 // We don't care about the particular error, so we ignore it with a `_`.
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};
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?
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>`".
59 // Notice that I called the function on `SomethingOrNothing` `print2` to disambiguate from the `print` defined previously.
61 // *Hint*: There is a macro `print!` for printing without appending a newline.
65 impl<T: Print> SomethingOrNothing<T> {
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.