X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/683f369ba51d22cb8b89ab31f1b20c01c117361c..5c86632a09410065f7ed67d8c965999edd4172a3:/src/part03.rs diff --git a/src/part03.rs b/src/part03.rs index 3dfb2ab..2085d34 100644 --- a/src/part03.rs +++ b/src/part03.rs @@ -30,7 +30,7 @@ fn read_vec() -> Vec { //@ concurrently, that also reads from standard input? The result would be a mess. Hence //@ Rust requires us to `lock` standard input if we want to perform large operations on //@ it. (See [the documentation](https://doc.rust-lang.org/stable/std/io/struct.Stdin.html) for - //@ more details.) + //@ more details.) for line in stdin.lock().lines() { // Rust's type for (dynamic, growable) strings is `String`. However, our variable `line` // here is not yet of that type: It has type `io::Result`. @@ -60,7 +60,6 @@ fn read_vec() -> Vec { //@ the return type of the function), but that's a bit too much magic for my taste. We are //@ being more explicit here: `parse::` is `parse` with its generic type set to `i32`. match line.trim().parse::() { - //@ `parse` returns again a `Result`, and this time we use a `match` to handle errors //@ (like, the user entering something that is not a number). //@ This is a common pattern in Rust: Operations that could go wrong will return @@ -102,7 +101,8 @@ pub fn main() { // **Exercise 03.1**: Define a trait `Print` to write a generic version of // `SomethingOrNothing::print`. -// Implement that trait for `i32`, and change the code above to use it. +// Implement that trait for `i32`, make `print2 use it, and change `main` above to use the new +// generic `print2` function. // I will again provide a skeleton for this solution. It also shows how to attach bounds to generic // implementations (just compare it to the `impl` block from the previous exercise). // You can read this as "For all types `T` satisfying the `Print` trait, I provide an implementation @@ -115,6 +115,9 @@ pub fn main() { pub trait Print { /* Add things here */ } +impl Print for i32 { + /* Add things here */ +} impl SomethingOrNothing { fn print2(self) { unimplemented!()