Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 3: Decisions

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.

Read one line, show it
use std::io;
 
fn main() {
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
println!("you typed: {}", line.trim());
}

Four new pieces, and you only need the idea of each for now.

  1. String::new() makes an empty piece of text that can grow. It is let mut because read_line is going to write into it.
  2. &mut line means "here, you may change this". The &mut lends the text out to be changed. Chapter 4 explains lending in full; for now, read it as "write your answer here".
  3. .unwrap() means "if reading failed, stop the program". Reading a keyboard practically never fails, and chapter 7 replaces it with something kinder anyway.
  4. .trim() removes whitespace (spaces, tabs and line breaks) at both ends. read_line keeps the Enter key you pressed as a newline at the end of the text, so without trim a typed /quit would arrive as /quit plus 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.

Real run, with the input piped in (cargo run -q hides the build chatter)
$ echo "hello there" | cargo run -q
you typed: hello there

Reading 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 into name_line, and trims it into name. 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 loop clears line, reads the next line, and leaves if the input has ended (0 bytes). A trimmed /quit says goodbye and leaves too. An empty line is skipped. Anything else is counted and answered by reply. The match, reply and HELP are 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.

Chatterbox v0.3 after lesson 3.4: the whole program (green lines are new in this lesson)
src/main.rs13 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 3);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /quit";
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// What the bot says back to one message.
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false; // true skips the greeting
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match message {
"" => {} // nothing typed: nothing to answer
"/help" => println!("bot: {}", HELP),
"/quit" => {
println!("bot: bye, {}!", name);
break;
}
other => {
messages_seen += 1;
println!("bot: {}", reply(other));
}
}
}
println!("messages so far: {}", messages_seen);
}
You type
Sam
hello there
/quit
Chatterbox prints (a real run)
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.

Try itYour turn: a chat session as text

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).

fn reply(msg: &str) -> String {
match msg {
"" => String::from("(nothing to say)"),
"/help" => String::from("commands: /help, /quit"),
other => format!("you: {other}"),
}
}
 
fn run_chat(input: &str) -> String {
let mut out = String::new();
for line in input.lines() {
let message = line.trim();
// TODO: /quit: add "bye!\n" and stop. Otherwise add reply(message) and a newline.
}
out
}
 
fn main() {
print!("{}", run_chat("hi\n/help\n/quit\nnever seen\n"));
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
Why call trim() on what read_line gave you?Reveal
The text still ends with the newline from pressing Enter, so "/quit" would not match "/quit" plus a newline.
What does read_line returning 0 mean?Reveal
The input has ended, so the loop should stop.
Why does the exercise take a &str of lines instead of reading the keyboard?Reveal
A function over text can be tested and run anywhere, including the Playground, which has no keyboard. The loop is the same.

That is lesson 3.4. Tick it off so the course remembers where you are.

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.

Learn Rust by building a chat app · Lesson 3.4 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026