liveBook · Manning

Pattern

As explained in Learn Rust in a Month of Lunches

Pattern is a Rust string-matching trait implemented by supported search patterns such as string slices, characters, and closures.

`Pattern` is a trait for inputs used to search strings. For example, `.match_indices()` accepts a string slice, a character, or a closure as its search pattern. It returns each match together with its index. section 9.1.4

fn main() {
    let some_str = "Er ist noch nicht erklärt. Aber es gibt Krieg. Verlaß
    dich drauf.";
    for (index, item) in some_str.match_indices(|c| c > 'z') {
        println!("{item} at {index}");
    }
    for (index, item) in some_str.match_indices(". ") {
        println!("'{item}' at index {index}");
    }
}

One search uses a closure to find characters; the other uses a string slice to find repeated punctuation. Both use `.match_indices()` to print matches and their indexes. section 9.1.4

You do not need to implement or inspect the trait to use these examples. The word “pattern” also appears in tuple destructuring and `match` arms; those examples concern matching values, not choosing a string-search input. section 9.1.4 section 3.1.3 section 3.2.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Identifies accepted input forms and demonstrates their use with `.match_indices()`, without explaining the trait’s internals.
Examples
Uses a closure to find characters and a string slice to find repeated punctuation, printing each match and index.
What it assumes
Assumes familiarity with strings and closures; introduces `Pattern` only as the trait that permits several search inputs.
What you can do after
Apply it via `.match_indices()` to search a string with a supported input and inspect the resulting matches and indexes.
How it connects
Connects string searching with string slices, characters, closures, and the indexed results of `.match_indices()`.

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.