0

I'm relatively new to Go, and in a bid to catch on quickly I tried rewriting some of my JavaScript(NodeJS) code in Go. Recently I hit sort of a stumbling block, where I found out that Go doesn't have ternary operators. For example in JavaScript I could do this:

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

query here represents Req.query

But I found out that I couldn't do the same with Go, I had to write an if-else statement. I'd just like to know what the reason is as to why this doesn't exist in Go world (of if there's some design principle as to why this is so)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
imadu
  • 69
  • 2
  • 6

1 Answers1

9

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.

See related: What is the idiomatic Go equivalent of C's ternary operator?

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827