Why Go Skips the Ternary Operator and How to Simulate It
The article explains why the Go language deliberately omits the ternary (?:) operator, compares its usage in Python, JavaScript, and C/C++, shows how to rewrite complex ternary expressions with clear if‑else statements, and presents a functional workaround while outlining the pros and cons of ternary syntax.
The ternary (?:) operator is common in many languages. In Python it appears as val = trueValue if expr else falseValue, in JavaScript as const val = expr ? trueValue : falseValue, and in C/C++ as const char *val = expr ? "trueValue" : "falseValue";.
Go, however, does not support this operator; attempting val := expr ? "trueValue" : "falseValue" triggers a compile‑time error invalid character U+003F '?'. The Go designers state that the operator is omitted because it encourages overly complex, hard‑to‑read expressions, and a single if‑else construct is sufficient for clarity.
Complex ternary expressions can become unreadable. For example, a nested JavaScript ternary that determines status and word values requires careful visual parsing. Converting it to explicit if statements makes the control flow evident:
let status = ''
if (type === 1) {
if (again === 1) {
status = '再售'
} else {
status = '已售'
}
} else {
status = '未售'
}
let word = ''
if (res.distance === 0) {
word = 'a'
} else if (res.distance === 1 && res.difference > 3) {
word = 'b'
} else if (res.distance === 2 && res.difference > 5 && String(res.key).length > 5) {
word = 'c'
} else {
word = 'd'
}To reduce nesting, the default value can be assigned first and only the necessary branches overridden, or else if can be used to flatten the structure.
For short, linear decisions, ternary syntax remains concise and readable, especially when combined with anonymous functions, e.g.,
const func = (age) => age > 18 ? '成年人' : '未成年人'. Python supports a similar one‑line conditional expression but disallows nesting.
Go’s philosophy of a fast, single‑pass compiler discourages adding such syntax. Nevertheless, a non‑recommended workaround defines a generic If function:
func If(cond bool, a, b interface{}) interface{} {
if cond {
return a
}
return b
}
age := 20
val := If(age > 18, "成年人", "未成年人").(string)This approach incurs performance overhead from interface conversion, requires explicit type assertions, and evaluates all arguments eagerly, which defeats the lazy evaluation benefit of true ternary operators.
Pros of the ternary operator: concise expression of simple conditions, reduced temporary variables, and lower mental overhead for straightforward cases. Cons: poor readability for complex logic, potential misuse to replace clear if statements, and inability to contain multiple statements per branch.
Ultimately, whether to use a ternary operator depends on the language’s design goals and the specific code context; in Go, the idiomatic choice is to stick with if‑else constructs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
