Sub topic 4
Trimming the trailing newline
This chapter assumes you can write a basic read_line program, you know the difference between String and &str, and you can run programs with cargo run.
Why the newline is there
read_line stores everything the user typed, including the Enter key. That key arrives as a newline character, \n. On Windows the terminal usually sends a carriage return and a newline together, \r\n. Both characters end up in your String.
Print the buffer with {:?} to see what is really in it:
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
println!("{input:?}");
Ok(())
}If you type hi and press Enter, the program prints "hi\n". The Debug format shows escape sequences, so invisible characters become visible.
The trim methods
str provides several methods that remove characters from the ends of a string. All of them return a &str that borrows from the original. None of them changes the original.
| Method | What it removes |
|---|---|
| `trim` | Whitespace at both ends |
| `trim_start` | Whitespace at the start only |
| `trim_end` | Whitespace at the end only |
| `strip_suffix('\n')` | Exactly one `\n`, returned as `Option<&str>` |
| `trim_end_matches(['\r', '\n'])` | Any run of `\r` and `\n` at the end |
Whitespace here means any Unicode whitespace: spaces, tabs, \r and \n. This program shows the differences:
fn main() {
let input = String::from(" yes\r\n");
println!("{:?}", input.trim());
println!("{:?}", input.trim_end());
println!("{:?}", input.trim_start());
println!("{:?}", input.strip_suffix('\n'));
}It prints:
"yes"
" yes"
"yes\r\n"
Some(" yes\r")strip_suffix('\n') leaves the \r behind on Windows line endings. In most programs plain trim is the right choice.
Common errors
The most common bug is comparing the raw buffer. The comparison below is always false, because the buffer holds "yes\n", not "yes":
use std::io;
fn main() -> io::Result<()> {
let mut answer = String::new();
io::stdin().read_line(&mut answer)?;
if answer == "yes" {
println!("never reached");
}
if answer.trim() == "yes" {
println!("confirmed");
}
Ok(())
}The second bug is expecting trim to change the string. It does not, so a bare input.trim(); statement does nothing useful. Use the returned value, or shadow the name:
let input = String::from("42\n");
let input = input.trim(); // the new binding is a &strThe third bug is a borrow error. trim returns a slice that points into the String. You cannot clear or modify the String while that slice is still in use. If you need a value that outlives the buffer, make an owned copy:
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let name = input.trim().to_string();
input.clear();
println!("Hello, {name}!");
Ok(())
}The last bug appears when you reuse one buffer in a loop. read_line appends to the String, so without input.clear() each new line is added after the previous ones.
Trim before you parse
Parsing a number is stricter than comparing text. "42\n".parse::<u32>() fails with an invalid digit error, because the newline is not a digit. Call trim first, as in input.trim().parse::<u32>(). The next chapter covers parsing in detail.
Exercise
A program reads one line with read_line into input, then runs println!("[{}]", input);. The user types abc and presses Enter. What is printed, and which one-method change makes it print [abc]?
Show answer
It prints [abc] followed by a line break inside the brackets, so the output is [abc on one line and ] on the next. The buffer holds "abc\n". Printing input.trim() instead, or input.trim_end(), removes the newline and gives [abc].
Exercise
Why does let n: u32 = input.parse().unwrap(); panic when input came from read_line and the user typed 7, and how do you fix it?
Show answer
input is "7\n", and the newline makes the parse fail. Fix it by trimming first: input.trim().parse().unwrap(). Handling the error with match is better than unwrap.