为什么 Go 没有三元条件运算符

Why Go doesn't have a ternary conditional operator

我是 Go 的新手,为了快速赶上进度,我尝试用 Go 重写一些 JavaScript(NodeJS) 代码。最近我遇到了一个绊脚石,我发现 Go 没有三元运算符。例如在 JavaScript 中我可以这样做:

const pageNumber: number = query.pageNumber ? parseInt(query.pageNumber, 10): 1;

query这里表示Req.query

但我发现我不能用 Go 做同样的事情,我必须写一个 if-else 语句。我只是想知道为什么 Go 世界中不存在这种情况的原因是什么(如果有一些设计原则为什么会这样)

Go FAQ: Why does Go not have the ?: operator?

There is no ternary testing operation in Go. You may use the following to achieve the same result:

if expr {
    n = trueVal
} else {
    n = falseVal
}

The reason ?: is absent from Go is that the language's designers had seen the operation used too often to create impenetrably complex expressions. The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.

查看相关内容:What is the idiomatic Go equivalent of C's ternary operator?