Is there a way to use custom patterns such as a re

2019-05-01 01:43发布

I'm 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'm 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 an if, else-if chain because as far as I can tell, Rust's match feature is limited to destructuring, enums, and type patterns. Is there a way to match on regexes 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 stay neat.

1条回答
Root(大扎)
2楼-- · 2019-05-01 02:00

No. The match patterns must be composed of things that can be statically verified by the compiler.

However, you can use a match guard:

fn rd_tree(chars: std::str::Chars) {
    while let Some(c) = chars.next() {
        match c {
            c if c.is_whitespace() => {}
            '(' => {}
            ')' => {}
            _ => {}
        }
    }
}

A match guard allows you to run a function against whatever the pattern matched.

查看更多
登录 后发表回答