What is the idiomatic Go equivalent of C’s ternary operator?

In Go, there is no direct equivalent of C’s ternary operator (condition ? trueValue : falseValue). Instead, Go’s language design promotes readability and simplicity, and it encourages the use of if-else statements for conditional expressions.

However, you can achieve a similar effect using a simple if-else statement. Here’s how you can write a Go equivalent of C’s ternary operator using an if-else statement:

package main

import "fmt"

func ternary(condition bool, trueValue, falseValue int) int {
    if condition {
        return trueValue
    }
    return falseValue
}

func main() {
    a, b := 10, 20

    // Equivalent to: int result = (a < b) ? a : b;
    result := ternary(a < b, a, b)
    fmt.Println("Result:", result)
}

Output:

Result: 10

In this example, we create a function named ternary that takes three arguments: the condition, the true value, and the false value. Inside the function, we use a simple if-else statement to return the true value if the condition is true or the false value if the condition is false.

Keep in mind that while this approach is similar to C’s ternary operator, the Go community generally prefers to use if-else statements for clarity and readability. Avoid overusing this pattern and choose whichever approach makes your code most understandable for others who read it.

error: Content is protected !!