实现说明
函数 parse_word、tokenize、main组织了整个示例的执行。
for c in input.chars() 承担全部的逐项处理。match 一条一条覆盖值的形态——不会意外落到默认分支上。
使用要点
- 跑完文件,输出里会留下标记——
token count:。 - 执行文件,
main会按顺序走完tokenize。
常见问题
运行「match 字符类别实现迷你分词器」会打印什么?
整个文件跑完,输出行以 token count: 这类前缀开头。
签名一览:fn parse_word(word: &str) -> Token
核心语句
fn parse_word(word: &str) -> Token {
// All digits -> Number, otherwise -> Ident
if word.chars().all(|c| c.is_ascii_digit()) {
Token::Number(word.parse().expect("digits only"))
} else {
Token::Ident(String::from(word))
}
}
代码示例
#[derive(Debug, PartialEq)]
enum Token {
Number(u32),
Ident(String),
Plus,
Dash,
}
fn parse_word(word: &str) -> Token {
// All digits -> Number, otherwise -> Ident
if word.chars().all(|c| c.is_ascii_digit()) {
Token::Number(word.parse().expect("digits only"))
} else {
Token::Ident(String::from(word))
}
}
fn tokenize(input: &str) -> Vec<Token> {
let mut tokens = Vec::new();
let mut word = String::new();
for c in input.chars() {
// Range and or-patterns: alphanumerics count as word characters
let is_word = matches!(c, '0'..='9' | 'a'..='z' | 'A'..='Z');
if !is_word && !word.is_empty() {
tokens.push(parse_word(&word));
word.clear();
}
match c {
// Literal patterns: single-character symbols emit a token immediately
'+' => tokens.push(Token::Plus),
'-' => tokens.push(Token::Dash),
'0'..='9' | 'a'..='z' | 'A'..='Z' => word.push(c),
// Wildcard arm: everything else is just a separator
_ => {}
}
}
if !word.is_empty() {
tokens.push(parse_word(&word));
}
tokens
}
fn main() {
let tokens = tokenize("height-42+width");
println!("{:?}", tokens);
assert_eq!(
tokens,
vec![
Token::Ident(String::from("height")),
Token::Dash,
Token::Number(42),
Token::Plus,
Token::Ident(String::from("width")),
]
);
println!("token count: {}", tokens.len());
}