Is there a way to use custom patterns like regex or functions in a match?
I am writing a toy programming language in Rust. I prototyped the parser logic in Ruby:
def rd_tree(chars)
loop do
case c = chars.next
when /\s/
# whitespace stuff
when "("
# open paren stuff
when ")"
# close paren stuff
else
# default stuff
end
end
end
And now I am converting it to Rust:
fn rd_tree(chars: std::str::Chars) {
while let Some(c) = chars.next() {
if c.is_whitespace() {
// whitespace stuff
} else if c == '(' {
// open paren stuff
} else if c == ')' {
// close paren stuff
} else {
// default stuff
}
}
}
I resorted to using the if, else-if chain because as far as I can tell, Rust's matching feature is limited to destructuring, enums, and template types. Is there a way to match regex or boolean functions? If not, is there a more idiomatic pattern here than if else-if? I expect the logic to have more branches in the future and I want it to remain neat.
source to share
Not yet. The match
samples should be made up of things that can be statically checked by the compiler.
However, you can use match defense:
fn rd_tree(chars: std::str::Chars) {
while let Some(c) = chars.next() {
match c {
c if c.is_whitespace() => {}
'(' => {}
')' => {}
_ => {}
}
}
}
Match protection allows you to run a function against any matched pattern.
In the future, persistent evaluation could be improved to allow function calls instead of templates:
#[derive(PartialEq, Eq)]
struct Foo { f: usize, g: usize }
const fn ZERO(x: usize) -> Foo { Foo { f: x, g: x } }
fn main() {
let f = Foo { f: 0, g: 1 };
match f {
ZERO(22) => println!("hi"),
_ => println!("1"),
}
}
This work is tracked in issue # 57240 . It's not immediately obvious to me how this would work with your specific example or regex without significant effort.
source to share