1 // Rust-101, Part 03: Input
2 // ========================
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
8 use std::io::prelude::*;
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 `io::stdin()`.
14 let stdin = io::stdin();
15 println!("Enter a list of numbers, one per line. End with Ctrl-D.");
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>`.
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`.
25 match line.parse::<i32>() {
29 // We don't care about the particular error, so we ignore it with a `_`.
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};
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?
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>`".
57 // Notice that I called the function on `SomethingOrNothing` `print2` to disambiguate from the `print` defined previously.
59 // *Hint*: There is a macro `print!` for printing without appending a newline.
63 impl<T: Print> SomethingOrNothing<T> {
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.