11.match
(我对部分段落进行翻译)
A match
statement is used to branch execution of a program. It’s the equivalent of the switch
statement found in many other languages, but offers some additional features.
match用于分支控制语句,它类同于switch,这和大多数语言类似,但是它有一些补充特征。
基本语法:
match [expression]:
[pattern](s):
[block]
[pattern](s):
[block]
[pattern](s):
[block]
Crash-course for people who are familiar with switch statements:
- 将
switch
替换为match
- 删除
case
- 删除任何
break` `。如果默认情况下不想 ``break
,可以使用continue
作为故障转移。 - 将
default
更改为单个下划线。
控制流:
The patterns are matched from top to bottom. If a pattern matches, the corresponding block will be executed. After that, the execution continues below the match
statement. If you want to have a fallthrough, you can use continue
to stop execution in the current block and check the ones below it.
有6中模式类型:
- 常数模式
-
常量原语,如数字和字符串:
match x: 1: print("We are number one!") 2: print("Two are better than one!") "test": print("Oh snap! It's a string!")
- 变量模式
-
匹配变量/枚举的内容:
match typeof(x): TYPE_FLOAT: print("float") TYPE_STRING: print("text") TYPE_ARRAY: print("array")
- 通配符模式
-
这个模式匹配所有内容。它被写成一个下划线。
在其他语言中,它可以用作
switch
语句中default
的等效项。:match x: 1: print("It's one!") 2: print("It's one times two!") _: print("It's not 1 or 2. I don't care tbh.")
- 绑定模式
-
绑定模式引入了一个新变量。与通配符模式类似,它匹配所有内容,并为该值提供一个名称。它在数组和字典模式中特别有用。:
match x: 1: print("It's one!") 2: print("It's one times two!") var new_var: print("It's not 1 or 2, it's ", new_var)
- 数组模式
-
matches an array. Every single element of the array pattern is a pattern itself, so you can nest them.
首先测试数组的长度,它必须与模式相同大小,否则模式不匹配。
开放式数组: 数组可以通过使最后一个子模式
..
大于模式每个子模式必须用逗号分隔。:
match x: []: print("Empty array") [1, 3, "test", null]: print("Very specific array") [var start, _, "test"]: print("First element is ", start, ", and the last is \"test\"") [42, ..]: print("Open ended array")
- 字典模式
-
工作方式与数组模式相同。每个键必须是一个常量模式。
首先测试字典的大小,它必须与模式的大小相同,否则模式不匹配。
开放式字典: 字典可以通过创建最后一个子模式
..
来大于模式每个子模式必须用逗号分隔。
如果不指定值,则只检查键的存在。
值模式与键模式之间用一个``:``分隔开
match x: {}: print("Empty dict") {"name": "Dennis"}: print("The name is Dennis") {"name": "Dennis", "age": var age}: print("Dennis is ", age, " years old.") {"name", "age"}: print("Has a name and an age, but it's not Dennis :(") {"key": "godotisawesome", ..}: print("I only checked for one entry and ignored the rest")
- 多重模式:
-
您还可以指定由逗号分隔的多个模式。这些模式中不允许有任何绑定。:
match x: 1, 2, 3: print("It's 1 - 3") "Sword", "Splash potion", "Fist": print("Yep, you've taken damage")