Skip to content

str::ends_with

str methods · Strings

Level: reference · for working programmers

One line: true if the string ends with the pattern — the mirror of starts_with, searching from the back.

pub fn ends_with<P: Pattern>(&self, pat: P) -> bool
where
    for<'a> P::Searcher<'a>: ReverseSearcher<'a>,

Stable since 1.0.0.

The signature carries an extra bound — the pattern's searcher must be a ReverseSearcher — which is why every method in this family that works backwards is spelled with a where clause. In practice all four usual pattern shapes satisfy it, so it never comes up until you write a generic function over P: Pattern and the compiler asks for the bound too.

As with the front, pair it with strip_suffix when the suffix is going to be removed.

File extensions are the classic misuse. name.ends_with(".rs") is a byte comparison: it is true for ".rs" itself, and it says nothing about case on filesystems where README.RS is the same file. Path::extension is the tool that knows what a filename is.

Example

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

fn main() {
    let file = "notes.tar.gz";

    println!("{}", file.ends_with(".gz"));
    println!("{}", file.ends_with('z'));
    println!("{}", file.ends_with(char::is_alphabetic));

    // Test and remove in one step.
    println!("{:?}", file.strip_suffix(".gz"));

    // Peeling two extensions.
    let mut name = file;
    while let Some(rest) = name.strip_suffix(".gz").or_else(|| name.strip_suffix(".tar")) {
        name = rest;
    }
    println!("stem = {name}");

    // A byte comparison, so case matters and a bare extension passes.
    println!("{} {} {}",
             "README.RS".ends_with(".rs"),
             "README.RS".to_lowercase().ends_with(".rs"),
             ".rs".ends_with(".rs"));
}

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

true
true
true
Some("notes.tar")
stem = notes
false true true

See also

str::ends_with in the standard library ↗

Po polsku

Szukanie od tyłu zostawia ślad w sygnaturze: where … P::Searcher<'a>: ReverseSearcher<'a> to dodatkowe ograniczenie, którego przy starts_with nie ma, a kompilator upomni się o nie dopiero wtedy, gdy sam napiszesz funkcję generyczną po P: Pattern — w zwykłym użyciu wszystkie cztery kształty wzorca je spełniają. Dla kogoś, kto ostrożnie podchodzi do operacji bajtowych na polskim tekście, jest tu wiadomość uspokajająca: ends_with nie jest w stanie rozciąć znaku, bo UTF-8 jest samosynchronizujący i bajt kontynuacji nigdy nie wygląda jak bajt początkowy, więc "żółw".ends_with("łw") po prostu działa. Prawdziwa pułapka leży gdzie indziej i strona pokazuje ją liczbami: to zwykłe porównanie bajtów, więc "README.RS".ends_with(".rs") daje false, a samo ".rs".ends_with(".rs")true. Do rozpoznawania rozszerzeń plików służy Path::extension, a gdy końcówka i tak ma zniknąć, strip_suffix sprawdza i usuwa za jednym razem.

Szukaj po polsku: sprawdzanie końcówki łańcucha · rozszerzenie pliku w Ruscie · rust str ends_with · rust strip_suffix · rust Path extension