Rust lang series episode #20 — reading from standard input (#rust-series)

in #rust-series8 years ago (edited)

Hello everyone, new episode of rust series is here. As we know enough language fundamentals today we can try something more practical. At this stage we will not deal with any GUI, we will have just a terminal or console. Common task here is to get some user data from terminal. Let’s read one line from standard input / terminal and write it back.

Reading from standard input

fn main() {
    use std::io::{self, BufRead};
    let stdin = io::stdin();
    println!("Type your name:");
    let line = stdin.lock().lines().next().unwrap().unwrap();
    print!("Hello {}!", line);
}

Breaking down

This is a simple version of reading from console. Let's go through it.

Reading from console is one of possible I/O operations. API for these kind of things is part of standard library under std::io module. Now let's break down the code a bit.

use imports named API, self and BufRead in this case. “self” will allow us to use std::io as just io. To use certain types, you need to import them. Some std types are imported by default and that’s why use is not necessary for them.

BufRead is trait for Read type that provides additional methods like lines() in our case.

io::stdin() constructs a new handle to the standard input of the current process. That’s the “place” from where we will read our string.

lock() locks this handle and return readable guard (implementing Read and BufRead). Lock is released when out of scope.

lines() return iterator over the lines of this reader. Iterator mechanism that can work over some sort of collection data.

next() is method of iterator that will return current element of collection and move to the next one.

unwrap() basically return wrapped result or panics. We call it twice because it’s “wrapped” twice. We already discussed this quite a lot in previous episode.

Note that you should handle result in a better way and you should not use unwrap unless you're 100% it's what you want. When we run this code, program will wait until we input some value.

Output

Type your name:
> steemiters

Hello steemiters!
Process finished with exit code 0

Cool, right? Well, ok, I know it's ultra-simple app but for the first time there is some interaction required from a user in our series.

Postfix

That's all for now, thank you for your appreciations, feel free to comment and point out possible mistakes (first 24 hours works the best but any time is fine). May Jesus bless your programming skills, use them wisely and see you next time.

Meanwhile, you can also check the official documentation for std:io API:

#rust-series
#rust-lang
#rust

Coin Marketplace

STEEM 0.19
TRX 0.13
JST 0.028
BTC 66052.74
ETH 3320.33
USDT 1.00
SBD 2.69