gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:30:45 26 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.

2年前关闭。




Improve this question




我对 Go 比较陌生,为了快速 catch ,我尝试在 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?

关于go - 为什么 Go 没有三元条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60561748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com