Skip to content

Commit

Permalink
Step 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Philipp Flenker committed Mar 31, 2024
1 parent 7a1753c commit 73c0e2a
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/main.rs
@@ -1,3 +1,8 @@
use std::io::{self, Read};

This comment has been minimized.

Copy link
@pflenker

pflenker Mar 31, 2024

Owner

In layman's terms, this line tells rust: "From the Standard Library ( std), I want to use Input and Output stuff (io)".
This line is a shorthand for:

use std::io;
use std::io::Read;

We will use io below, but we won't use Read, so why import it here?
In short, it's a Trait, something we will revisit a bit later.
In a nutshell, Read brings the implementation for bytes with it. Try removing it and see what happens.


fn main() {
println!("Hello, world!");
for b in io::stdin().bytes() {

This comment has been minimized.

Copy link
@pflenker

pflenker Mar 31, 2024

Owner

What this line does is can be stated as: "For every byte you can read from the keyboard, bind it to b and execute the following block".
This is what the individual pieces do:

  • io represents Input/Output, we imported this above.
  • ::stdin() calls the function stdin() on io, which represents the Standard Input.

Calling bytes() on io::stdin() returns something we can iterate over, or
in other words: Something which lets us perform the same task on a series of
elements. In Rust, same as many other languages, this concept is called an
Iterator.

Using an Iterator allows us to build a loop with for..in. With for..in in combination with bytes(), we are asking rust to read byte from the standard input into the variable b, and to keep doing it until there are no more bytes
to read. More on that in a second back in the tutorial text.

let c = b.unwrap() as char;
println!("{}", c);

This comment has been minimized.

Copy link
@pflenker

pflenker Mar 31, 2024

Owner

These two lines basically print out the character that was read - we'll describe this more thoroughly in a bit (and I promise, I'll explain unwrap and println! in due time!)

}
}

0 comments on commit 73c0e2a

Please sign in to comment.