Sub topic 2
Reading one line with read_line
This chapter assumes you know basic Rust syntax, how String and &mut references work, and how to handle a Result with match. You should also be able to run a program with cargo run. Here you will read one line of text from the keyboard and learn what read_line does to your String.
The smallest complete program
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
println!("You typed: {}", input.trim());
}io::stdin() returns a handle to the process's standard input. read_line is a method on that handle. It blocks until the user presses Enter, or until the input source ends, and then copies the text into your buffer.
What read_line does
The signature is fn read_line(&self, buf: &mut String) -> io::Result<usize>. Three details matter:
- It appends. The new text goes to the end of
buf. It does not replace what is already there. - It keeps the newline. If the user types
hiand presses Enter, the buffer holds"hi\n". On Windows the ending is usually"\r\n". - It returns the number of bytes read. That is
3for"hi\n". The count is bytes, not characters.
You can see all three by printing the buffer with {:?}, which shows escape sequences:
use std::io;
fn main() {
let mut input = String::new();
let bytes = io::stdin()
.read_line(&mut input)
.expect("failed to read line");
println!("read {bytes} bytes: {input:?}");
}Typing hi and pressing Enter prints read 3 bytes: "hi\n".
Why the buffer must be mutable
read_line writes into your string, so you pass &mut input, and the variable must be declared let mut. Leaving out mut or the &mut is the most common compile error here. The compiler message points at the call and suggests the fix.
The append behavior in practice
Because read_line appends, reusing one String across calls accumulates text:
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("failed to read line");
io::stdin().read_line(&mut input).expect("failed to read line");
println!("{input:?}");
}If you type a, Enter, b, Enter, the output is "a\nb\n". When you read in a loop, either create a new String on each pass or call input.clear() before each read. Otherwise old input leaks into the new parse.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Compile error about borrowing as mutable | `input` declared without `mut`, or `&mut` missing at the call | Use `let mut input` and pass `&mut input` |
| Warning: unused `Result` that must be used | The return value was ignored | Call `.expect(...)` or use `?` |
| Comparison with `"yes"` always fails | The buffer is `"yes\n"` | Compare `input.trim()` instead |
| Text from earlier reads appears | The buffer was not cleared | Call `input.clear()` or make a new `String` |
| Runtime error on odd input | The bytes are not valid UTF-8 | Handle the `Err` instead of using `expect` |
read_line returns an Err when the underlying read fails. It also returns an Err with kind InvalidData when the input is not valid UTF-8, because it must produce a String. Later chapters cover the Result in more detail, along with trimming and end of input.
A note on stdin() and buffering
Each call to io::stdin() gives you a handle to the same shared, buffered input. Calling it twice, as in the append example, does not lose data. The buffer lives in the process-wide stdin, not in the handle. You can store the handle in a variable if you prefer:
use std::io;
fn main() {
let stdin = io::stdin();
let mut first = String::new();
let mut second = String::new();
stdin.read_line(&mut first).expect("failed to read line");
stdin.read_line(&mut second).expect("failed to read line");
println!("{} / {}", first.trim(), second.trim());
}Exercise
A program calls read_line once and the user types "42" and presses Enter. What are the return value (inside Ok) and the contents of the String?
Show answer
The return value is 3, the number of bytes read, and the String holds "42\n" (on Windows, "42\r\n" and a count of 4). The newline is part of both.
Exercise
A loop reads a line, prints it, and repeats, using one String declared before the loop. On the second pass the output contains the first line too. What is the cause, and what is the fix?
Show answer
read_line appends to the buffer, so the first line is still there. Call input.clear() at the start of each pass, or declare a new String inside the loop.