Lesson 3.4 · 11 min
Reading a line
Chatterbox has been talking to a pretend list. This lesson plugs in the keyboard: it asks your name, reads a line you type, answers it, and goes back for the next, until you type /quit.
Adds to ChatterboxChatterbox asks your name and reads what you type.
Where input comes from
The line use std::io; at the top brings Rust's input and output tools into reach, so you can write io::stdin() instead of the full path.
A program has an input stream, called standard input or stdin. When you run a program in a terminal, whatever you type goes there. To pull one line out of it you call read_line.
The in-browser runner on this page has no keyboard to read, so this lesson works in two halves. First the real program, which you run in your own terminal. Then the same thinking as a function over text, which you can test here.
Four new pieces, and you only need the idea of each for now.
String::new()makes an empty piece of text that can grow. It islet mutbecauseread_lineis going to write into it.&mut linemeans "here, you may change this". The&mutlends the text out to be changed. Chapter 4 explains lending in full; for now, read it as "write your answer here"..unwrap()means "if reading failed, stop the program". Reading a keyboard practically never fails, and chapter 7 replaces it with something kinder anyway..trim()removes whitespace (spaces, tabs and line breaks) at both ends.read_linekeeps the Enter key you pressed as a newline at the end of the text, so withouttrima typed/quitwould arrive as/quitplus a newline, and would match no arm.
That last point is worth checking by eye. Here is a real run with the input piped in: instead of typing, the | sign feeds the output of one command (echo, which just repeats its text) into the program as if you had typed it.
$ echo "hello there" | cargo run -q
you typed: hello thereReading until there is nothing left
read_line also returns how many bytes it read. When the input has ended (you pressed Ctrl-D on a Mac or Linux, or Ctrl-Z then Enter on Windows, or a pipe ran dry) that number is 0. A chat loop has to notice, or it spins forever on empty reads. So the loop has two ways out: the user types /quit, or the input ends.
Before the loop, one more important piece: line.clear() at the top of each turn. read_line adds to what is there, it does not replace it.
Chatterbox v0.3, finished
Here is the whole program. The pretend list from lesson 3.3 is gone, and two reads take its place.
- Your name first. Right after the banner, Chatterbox asks
What should I call you?, reads one line intoname_line, and trims it intoname. Until now the name was written in as"Sam"; now it is whatever you type, and the greeting and the goodbye both use it. - Then the chat loop. A
loopclearsline, reads the next line, and leaves if the input has ended (0 bytes). A trimmed/quitsays goodbye and leaves too. An empty line is skipped. Anything else is counted and answered byreply. Thematch,replyandHELPare exactly as lesson 3.3 left them: only the source of the lines changed.
The Run buttons on this page cannot type into a program, so the conversation under the code is a real run instead: the lines under You type were fed in one by one, exactly as if typed at a keyboard, and the other side is what Chatterbox really printed. To talk to it yourself, download the zip and use cargo run in your own terminal.
Sam hello there /quit
Chatterbox v0.3 What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: you said: hello there bot: bye, Sam! messages so far: 1
Download this version (zip)Unzip, then cargo run inside the folder.
Finish run_chat. For each line of input: trim it, stop at /quit (adding bye! first), otherwise add reply(message). Every output line ends with a newline, written \n: inside quotes, those two characters stand for the one invisible newline character that pressing Enter makes, so "bye!\n" is bye! and then a line break. main shows the result with print!, which is println! without the line break at the end (the text already ends with one).
Finish run_chat. For each line of input: trim it, stop at /quit (adding bye! first), otherwise add reply(message). Every output line ends with a newline, written \n: inside quotes, those two characters stand for the one invisible newline character that pressing Enter makes, so "bye!\n" is bye! and then a line break. main shows the result with print!, which is println! without the line break at the end (the text already ends with one).
Hidden tests (4): no_input_no_output echoes_and_helps quit_stops_the_chat whitespace_is_trimmed
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
Chapter 3 is done and Chatterbox is a real, if shy, chat program. It asks your name, reacts to what you type, knows two commands, has an answer for questions and for messages that are too long, and its logic is in functions you can test. Everything it says is text it holds for a moment and forgets.
Look at the names in main one more time: messages_seen is a number, but name_line and line are Strings that grow to fit whatever you type, and you never said how big. Chapter 4 opens the lid on that: where values like these actually live in the computer's memory, and the idea Rust is built around, ownership.
Say it out loud, then reveal
Why call trim() on what read_line gave you?Reveal
What does read_line returning 0 mean?Reveal
Why does the exercise take a &str of lines instead of reading the keyboard?Reveal
That is lesson 3.4. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
How do I read user input in Rust?
Make an empty String, then call std::io::stdin().read_line with a changeable reference to it. The typed line, including the Enter key, is added to that String.
Why does my Rust input not match even though I typed the right word?
read_line keeps the newline from pressing Enter at the end of the text. Call trim() on it before comparing, and "/quit" will match.
What is stdin?
Standard input: the stream a program reads from. When you run a program in a terminal, whatever you type goes there.
Why do I need line.clear() inside the loop?
read_line adds to whatever is already in the String rather than replacing it. Clearing it at the start of each turn stops old lines from piling up.