提问人:Blazing Blast 提问时间:4/13/2023 更新时间:4/13/2023 访问量:37
如何使用模式功能进行匹配?[复制]
How to use pattern funtions to in matching? [duplicate]
问:
我正在尝试查看在这种情况下是否可以使用 match 而不是 if-else,这是我希望能够编写的代码
let c : char = 'c';
let tt: TokenType = match c {
is_alphanumeric(c) => TokenType::Identifier,
is_whitespace(c) => TokenType::Whitespace,
_otherwise => TokenType::Operator
};
// These are methods of char
pub fn is_alphanumeric(self) -> bool {}
pub fn is_whitespace(self) -> bool {}
如果-elses看起来像
let c : char = 'c';
let mut mut_tt : TokenType;
if c.is_alphabetic() {mut_tt = TokenType::Identifier;}
else if c.is_whitespace() {mut_tt = TokenType::Whitespace;}
else {mut_tt = TokenType::Operator;}
let tt : TokenType = mut_tt;
有什么方法可以让它与匹配一起工作吗?我什至应该想要吗?
答:
0赞
Blazing Blast
4/13/2023
#1
我发现这完全符合我的意愿
let tt: TokenType = match c {
i if i.is_alphanumeric() => Some(TokenType::Identifier),
w if w.is_whitespace() => Some(TokenType::Whitespace),
_ => Some(TokenType::Operator)
}};
评论
match