4.9 控制流 (Control Flow)
if
表达式 (if
expressions)
if
表达式 (if
expressions)Sway supports if, else, and else if expressions that allow you to branch your code depending on conditions.
Sway 支持 if、else 和 else if 表达式,允许你根据条件分支代码。
For example: 例如:
在 let
语句中使用 if
(Using if
in a let
statement)
let
语句中使用 if
(Using if
in a let
statement)Like Rust, if
s are expressions in Sway. What this means is you can use if
expressions on the right side of a let
statement to assign the outcome to a variable.
与 Rust 一样,if
是 Sway 中的表达式。这意味着您可以在 let
语句的右侧使用 if
表达式将结果分配给变量。
Note that all branches of the if
expression must return a value of the same type.
请注意,if
表达式的所有分支都必须返回相同类型的值。
match
表达式 (match
expressions)
match
表达式 (match
expressions)Sway supports advanced pattern matching through exhaustive match
expressions. Unlike an if
statement, a match
expression asserts at compile time that all possible patterns have been matched. If you don't handle all the patterns, you will get compiler error indicating that your match
expression is non-exhaustive.
Sway 通过详尽的match 匹配
表达式支持高级模式匹配。与 if
语句不同,match
表达式断言在编译时**所有可能的模式都已匹配。如果您不处理所有模式,您将收到编译器错误,表明您的match 匹配
表达式是非穷尽的。
The basic syntax of a match
statement is as follows:
match
语句的基本语法如下:
Some examples of how you can use a match statement:
有关如何使用匹配语句的一些示例:
循环 (Loops)
while
while
Loops in Sway are currently limited to while
loops. This is what they look like:
Sway 中的循环目前仅限于while
循环。他们看起来像这样:
You need the while
keyword, some condition (value < 10
in this case) which will be evaluated each iteration, and a block of code inside the curly braces ({...}
) to execute each iteration.
您需要 while
关键字、每次迭代都会评估的某些条件(在本例中为 value < 10
),以及花括号内的代码块({...}
)来执行每次迭代。
break
和 continue
(break
and continue
)
break
和 continue
(break
and continue
)break
and continue
keywords are available to use inside the body of a while
loop. The purpose of the break
statement is to break out of a loop early:
break
和 continue
关键字可在 while 循环体内使用。 break
语句的目的是尽早跳出循环:
The purpose of the continue
statement is to skip a portion of a loop in an iteration and jump directly into the next iteration:
continue
语句的目的是跳过迭代中的一部分循环并直接跳转到下一次迭代:
嵌套循环 (Nested loops)
You can also use nested while
loops if needed:
如果需要,您还可以使用嵌套的 while
循环:
Last updated