Loading AI tools
来自维基百科,自由的百科全书
在计算机程序设计中,卫(guard)是布尔表达式,其结果必须为真,程序才能执行下去。卫语句(guard code或guard clause)用于检查先决条件。卫语句的用途,例如:
卫语句可用于子进程的提前退出(early exit),这是结构化程序设计的一种常见偏离,可删除一层嵌套使得代码更扁平:[1] 把if guard { ... }
替代为:if not guard: return; ...
.
在APL、Haskell、Clean、Erlang、occam、Promela、OCaml、Swift[2]与Scala程序设计语言中,这一术语有特殊含义。
Mathematica中,卫被称为约束(constraints)。
在增强的模式匹配中,卫语句用于跳过一些即使结构匹配的模式。
条件语句中的布尔表达式也符合卫的定义,虽然被称作“条件”。
下述Haskell语言的例子,卫出现在每对"|"与"="之间:
f x
| x > 0 = 1
| otherwise = 0
这类似于如下的数学表示的"if"与"otherwise" 子句就是卫语句:
如果有多个平行的卫语句,则按照自顶向下顺序,第一个通过的分支被选择。
public string Foo(string username) {
if (username == null) {
throw new ArgumentNullException(nameof(username));
}
// Rest of the method code follows here...
}
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.