Ternary Expressions with Go Generics

A ternary expression is a common logical construct available in many programming languages. It shortens an if/else condition into a single statement:

someCondition ? "yes" : "no"

In the above example, ? means “then” and : means “else”, so the example reads if someCondition is true, then use "yes", otherwise use "false".

When the Go 2 proposals were being considered, there were a number of proposals for the addition of ternary expressions into the language proposed by the community:

Being a fairly trival logical operator to simulate with basic if/else conditions, it was largely dismissed by the community and the Go team but coming from a C# background, I’d consider myself a fan of the construct (although appreciate why it wouldn’t/shouldn’t have a home in Go).

A ternary operator can be simulated in Go as follows:

package main

import "fmt"

func main() {
	someCondition := true
  
	a := "no"
	if someCondition {
		a = "yes"
	}

	fmt.Println(a)
}

It’s elegant enough but rather than a single-line ternary expression, we’re having to read 5 lines of code.

Skip forward a year and the Go 2 generics proposal is available in the go2goplay playground and with it, a more elegant way to implement ternary expressions. In the following example, I harness generics to create a very simple replacement for a full ?: ternary expression:

package main

import (
	"fmt"
)

func cond[type T](c bool, i, e T) T {
	if c {
		return i
	}
	return e
}

func main() {
  someCondition := true
  
  fmt.Println(cond(someCondition, "yes", "no"))
}

This example probably didn’t require a blog post but I like how the humble ternary expression can be created with the use of Go 2’s generics!

https://go2goplay.golang.org/p/MMYRVrEvSwA