Sub topic 2
Reading one line with read_line
This chapter covers read_line, the method that does the actual reading from standard input. It assumes you can write basic Rust (variables, functions, match), that you know String is an owned, growable text buffer and &mut is a mutable reference, and that you have a handle from io::stdin(). You should also know Result at a basic level and be able to run programs with cargo run.
What read_line does
read_line reads bytes from standard input up to and including the next newline character (\n). It appends those bytes to a String you provide. It returns how many bytes it added.
Here is the signature as it appears on Stdin:
fn read_line(&self, buf: &mut String) -> io::Result<usize>buf: &mut Stringis the destination. The method borrows your string mutably and grows it.- The return type is
io::Result<usize>. On success, theusizeis the number of bytes appended. On failure, you get anio::Error. The next chapter covers how to handle that result in detail. Here we useexpect, which stops the program with a message if the read fails.
The smallest useful program shows all three things: the buffer, the count, and the newline.
use std::io;
fn main() {
let mut input = String::new();
let count = io::stdin()
.read_line(&mut input)
.expect("failed to read line");
println!("bytes read: {count}");
println!("buffer: {input:?}");
}If you run this and type hi followed by Enter, the output is:
bytes read: 3
buffer: "hi\n"The count is 3 because the line is h, i, and the newline. The {input:?} format prints the string in Debug form, which shows the \n instead of silently moving to the next line. Use Debug formatting whenever you want to see exactly what is in a buffer.
How the data flows
The terminal does not send your keystrokes to the program one at a time. In the usual line-buffered mode, the terminal collects what you type and delivers it only when you press Enter. This is why read_line appears to wait until you finish a line. Your program is blocked inside the call until the operating system has a full line to give it.
When input is piped from a file or another program, there is no Enter key. The data is just available, and read_line returns as soon as it has found a newline in it.
The newline stays in the buffer
read_line does not strip the line ending. The newline is part of what it read and is kept in your String. This surprises many people the first time. It affects comparisons:
use std::io;
fn main() {
let mut answer = String::new();
io::stdin()
.read_line(&mut answer)
.expect("failed to read line");
if answer == "yes" {
println!("matched without trimming");
} else {
println!("no match, buffer is {answer:?}");
}
}Typing yes and pressing Enter prints no match, buffer is "yes\n". The comparison fails because the buffer is "yes\n", not "yes". The chapter on trimming covers the fix. For now, remember that what you read is the raw line, terminator included.
On Windows, a terminal or a file may use \r\n as the line ending. In that case the buffer ends with both characters, and read_line still stops only at \n. So the trailing \r is also part of your data.
read_line appends; it never clears
The method adds to the end of the string. It does not replace what is already there. If you reuse one String for two reads without emptying it, the lines pile up:
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 one, Enter, two, Enter, the program prints "one\ntwo\n". Both lines are in one buffer.
This matters most in loops. You have two sound options:
- Create a new
Stringon each iteration. This is simple and clear. - Declare the
Stringonce outside the loop and callinput.clear()before each read. This reuses the allocation, which avoids repeated memory allocation when you read many lines.
use std::io;
fn main() {
let stdin = io::stdin();
let mut line = String::new();
for round in 1..=2 {
line.clear();
stdin.read_line(&mut line).expect("failed to read line");
println!("round {round}: {line:?}");
}
}clear sets the length to zero but keeps the capacity, so the next read can reuse the same memory. Forgetting clear is the most common bug with the reuse pattern, and the symptom is a buffer that grows with old lines stuck in front of the new one.
The return value is a byte count
The usize in Ok(n) counts bytes, not characters. For plain ASCII text the two are the same. For other text they differ, because Rust strings are UTF-8, where one character can take up to four bytes.
If you type é and press Enter, the buffer is "é\n". The letter é takes two bytes in UTF-8 and the newline takes one, so read_line returns Ok(3) even though you typed one character.
| You type | Buffer contents | Bytes returned |
|---|---|---|
| `hi` and Enter | `"hi\n"` | 3 |
| Enter only | `"\n"` | 1 |
| `é` and Enter | `"é\n"` | 3 |
An empty line gives Ok(1), not Ok(0). The value Ok(0) is reserved for a different situation, where no more input exists at all. A later chapter in this tutorial covers detecting that case. For now, notice that "the user pressed Enter on a blank line" and "there is nothing left to read" look different in the return value, and keep them apart in your mind.
Text only: invalid UTF-8 is an error
Because read_line fills a String, the bytes it reads must be valid UTF-8. If the input contains bytes that are not, the call returns Err with kind io::ErrorKind::InvalidData. This can happen when you pipe in a binary file or a file in an older encoding. If an error occurs partway through, the buffer may already hold some of the data read so far, so do not rely on its contents after a failure.
If you need to read arbitrary bytes, read_line is the wrong tool. Reading into a Vec<u8> with Read or BufRead methods avoids the UTF-8 requirement. This tutorial stays with text.
Stdin and StdinLock both have read_line
You can call read_line in two places. It exists directly on Stdin, the value returned by io::stdin(). It also exists on StdinLock through the BufRead trait, which you get from stdin.lock().
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut first = String::new();
stdin.read_line(&mut first).expect("failed to read line");
let mut handle = stdin.lock();
let mut second = String::new();
handle.read_line(&mut second).expect("failed to read line");
println!("{first:?} then {second:?}");
}The behavior is the same. The difference is when the lock is taken. Standard input is shared by the whole process, so access to it is guarded by a lock. Calling read_line on Stdin takes the lock for the duration of that one call. Locking once with lock() holds it across many calls, which is the better fit when you read many lines in a row. Importing BufRead is required to call read_line on the lock, which is why the use line above names it.
Both handles share one internal buffer, so lines are not lost when you switch between them, as the example shows.
Edge cases to keep in mind
- Blocking. The call waits until a line or the end of input arrives. A program with no input on a terminal will sit there until you type.
- Last line without a newline. If the input ends without a final
\n,read_linereturns what is left, with no newline in the buffer. Your code should not assume every line ends in\n. - Very long lines. The method reads until it finds a newline, so a huge line with no newline grows the string without a limit. For untrusted input, consider a bounded approach.
- Existing buffer content. Whatever was in the
Stringbefore stays. Only the new bytes are counted in the return value, not the total length.
Summary of behavior
read_line(&mut buf)appends one line, including its line ending, tobuf.- It returns
Ok(n), wherenis the number of bytes added. - It blocks until a line (or the end of input) is available.
- It never clears the buffer, so reused buffers need
clear(). - The data must be valid UTF-8 or the call fails.
Exercise
A program creates let mut line = String::new(); once, then calls stdin.read_line(&mut line) in a loop without clearing it. The user types a, Enter, bc, Enter. What are the two return values and the contents of line after the second call?
Show answer
The first call returns Ok(2) ("a" plus the newline), and the buffer is "a\n". The second call returns Ok(3) ("bc" plus the newline), because the return value counts only the bytes appended by that call. The buffer is now "a\nbc\n", since read_line appends and never clears.
Exercise
A user types the single character ü (two bytes in UTF-8) and presses Enter. What does read_line return, and why is it not Ok(1)?
Show answer
It returns Ok(3). The return value counts bytes, not characters. The character ü takes two bytes in UTF-8 and the newline takes one, so three bytes are appended: the buffer is "ü\n".