Skip to content

str::trim_end

str methods · Strings

Level: reference · for working programmers

One line: trim at the back only — trailing whitespace removed, leading whitespace kept.

pub fn trim_end(&self) -> &str

Stable since 1.30.0.

The mirror of trim_start, and renamed from trim_right in the same 1.33 release for the same reason: "end" is a position in the bytes, "right" is a position on the screen.

This is the one you want when reading lines from input: it removes the \n (and a Windows \r\n) while leaving any leading indentation, which is usually meaningful. read_line keeps the newline, so line.trim_end() is the standard follow-up — trim() would also eat the indentation.

Trailing whitespace is also the invisible cause of most "why doesn't this match" bugs in config parsing, since "value " and "value" are different strings.

Example

str_trim_end.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let line = "    value  \r\n";
    println!("{:?}", line.trim_end());
    println!("{:?}", line.trim());

    // Reading a line: drop the newline, keep the indentation.
    for raw in ["    nested\n", "top\r\n"] {
        println!("{:?} -> {:?}", raw, raw.trim_end());
    }

    // The invisible mismatch trailing space causes.
    let stored = "value ";
    println!("{} {}", stored == "value", stored.trim_end() == "value");

    // Trailing-whitespace cleanup across a block.
    let messy = "a   \nb\t\nc\n";
    let clean: Vec<&str> = messy.lines().map(str::trim_end).collect();
    println!("{clean:?}");
}

Verified output of str_trim_end.rs — regenerated by tools/run_examples.py, never hand-typed.

"    value"
"value"
"    nested\n" -> "    nested"
"top\r\n" -> "top"
false true
["a", "b", "c"]

See also

str::trim_end in the standard library ↗

Po polsku

Nazwa znaczy tu więcej, niż się wydaje: trim_right przemianowano w 1.33 na trim_end, bo „koniec” jest miejscem w bajtach, a „prawo” miejscem na ekranie — dla polszczyzny wychodzi na jedno, ale dla pisma arabskiego czy hebrajskiego już nie, więc std wybrało nazwę niezależną od kierunku pisma. Sięga się po nią przede wszystkim przy czytaniu wierszy z wejścia: read_line zostawia \n, więc line.trim_end() jest naturalnym następnym krokiem, zdejmuje przy okazji windowsowe \r\n i zachowuje wcięcie — samo trim() zjadłoby także wcięcie, a ono zwykle coś znaczy. Drugie codzienne zastosowanie to tropienie niewidzialnych niezgodności w plikach konfiguracyjnych: "value " i "value" to dwa różne łańcuchy znaków, a spacja na końcu wiersza nie rzuca się w oczy w żadnym edytorze.

Szukaj po polsku: obcinanie końca łańcucha · spacja na końcu wiersza · rust trim_end vs trim · rust read_line trailing newline