🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
枚举可以以一个自然的方式通过它们的构造器进行匹配: > Enums can be matched by their constructors in a natural way: ~~~ var myTree = Node(Leaf("foo"), Node(Leaf("bar"), Leaf("foobar"))); var match = switch(myTree) { // matches any Leaf case Leaf(_): "0"; // matches any Node that has r = Leaf case Node(_, Leaf(_)): "1"; // matches any Node that has has // r = another Node, which has // l = Leaf("bar") case Node(_, Node(Leaf("bar"), _)): "2"; // matches anything 12 case _: "3"; } trace(match); // 2 ~~~ 模式匹配器会检查每个 case ,从头至尾,采用第一个匹配输入值的 case 。下面关于case规则的说明解释帮助你理解该过程: > The pattern matcher will check each case from top to bottom and pick the first one that matches the input value. The following manual interpretation of each case rule helps understanding the process: case Leaf(\_):匹配失败,因为 myTree 是一个i额 Node case Node(\_,Leaf(\_)):匹配失败,因为myTree右侧的子树不是一个Leaf,而是另一个 Node **case Node(\_,Node(Leaf("bar"),\_))**:匹配成功 **case \_**:不被检查,因为前一行已经匹配成功 > **case Leaf(\_)**: matching fails because myTree is a Node > **case Node(\_, Leaf(\_))**: matching fails because the right sub-tree of myTree is not a Leaf, but another Node > **case Node(\_, Node(Leaf("bar"), \_))**: matching succeeds > **case \_**: this is not checked here because the previous line matched