← 中文资源

简体中文版本

用 match 分支统计元音与辅音

match 结合或模式与守卫逐字符分类:多个字面量共用元音分支、is_ascii_alphabetic 守卫归辅音、一次遍历得到三类计数。"Hello, Rust 2026!" 里逗号、空格与数字全落进 other 臂,不与字母混淆。

阅读英文原文

实现说明

逻辑集中在函数 tally、main里。 for c in text.chars() 承担全部的逐项处理。输入的每种形态各占一个 match 分支,编译器检查这套分支是否完整。

使用要点

  • 每一步打印都带着自己的标签:empty。
  • 运行整个文件:main 会依次驱动 tally。

常见问题

运行「用 match 分支统计元音与辅音」会打印什么?

整个文件跑完,输出行以 empty 这类前缀开头。

签名一览:fn tally(text: &str) -> Tally

核心语句

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"),
}

代码示例

#[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"),
    }
}