我可以在python中使用rust的火柴吗?

时间:2019-11-29 04:44:23

标签: python rust match

我想在python3中使用rust match

代替if ... elif语句。

https://doc.rust-lang.org/rust-by-example/flow_control/match.html

fn main() {
    let number = 13;
    // TODO ^ Try different values for `number`

    println!("Tell me about {}", number);
    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13...19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
    }

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => 0,
        true => 1,
        // TODO ^ Try commenting out one of these arms
    };

    println!("{} -> {}", boolean, binary);
}

1 个答案:

答案 0 :(得分:1)

感谢您的提示,安德里亚·科贝里尼(Andrea Corbellini)。

我找到了解决方案,有pampy

from pampy import match, _

def func(x):
    return match(x,
          1, "One!",
          # 2 | 3 | 5 | 7 | 11, "This is a prime",     # not work
          # 2 or 3 or 5 or 7 or 11, "This is a prime", # not work
          2, "This is a prime",
          _, "Ain't special"
    )

if __name__ == '__main__':
    print("1: {}".format(func(1)))
    print("2: {}".format(func(2)))
    print("3: {}".format(func(3)))
    print("5: {}".format(func(5)))
    print("7: {}".format(func(7)))
    print("nothing: {}".format(func("nothing")))