Count Vowels And Consonants With Match
Classify each char through a match with or-patterns and guards, tallying vowels, consonants, and non-letters in one pass.
Code
#[derive(Debug, Default)]
struct Tally {
vowels: usize,
consonants: usize,
other: usize,
}
fn tally(text: &str) -> Tally {
let mut t = Tally::default();
for c in text.chars() {
match c.to_ascii_lowercase() {
// 或模式:多个字面量共用一个分支
'a' | 'e' | 'i' | 'o' | 'u' => t.vowels += 1,
c if c.is_ascii_alphabetic() => t.consonants += 1,
_ => t.other += 1,
}
}
t
}
fn main() {
let result = tally("Hello, Rust 2026!");
println!("{result:?}");
// 或模式也用于值匹配:直接判断首字母类别
let word = "octave";
match word.chars().next() {
Some('a' | 'e' | 'i' | 'o' | 'u') => println!("{word} starts with a vowel"),
Some(c) if c.is_alphabetic() => println!("{word} starts with a consonant"),
Some(_) => println!("{word} starts with a non-letter"),
None => println!("empty"),
}
}How the snippet works
Count Vowels And Consonants With Match keeps everything in the functions tally and main.
The loop for c in text.chars() is the only repeated construct. A match spells out every case; omit one and the code does not compile.
What to watch for
- Dependency-free by construction — no registry, no lockfile entry.
Applying it
The entry-point signature is fn tally(text: &str) -> Tally
The file’s steps show up in the output as empty.
The entry point wires tally together — run it once and the whole demo flows.
Statements that matter
match c.to_ascii_lowercase() {
// 或模式:多个字面量共用一个分支
'a' | 'e' | 'i' | 'o' | 'u' => t.vowels += 1,
c if c.is_ascii_alphabetic() => t.consonants += 1,
_ => t.other += 1,
}
match word.chars().next() {
Some('a' | 'e' | 'i' | 'o' | 'u') => println!("{word} starts with a vowel"),
Some(c) if c.is_alphabetic() => println!("{word} starts with a consonant"),
Some(_) => println!("{word} starts with a non-letter"),
None => println!("empty"),
}
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Count Vowels And Consonants With Match print when run?
- Invoke the file as-is — the `empty` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.