Skip to content

Instantly share code, notes, and snippets.

@ttys3
Forked from thanhminhmr/README.md
Created March 26, 2025 16:55
Show Gist options
  • Save ttys3/a4786eb2dff87b4e62d1d711da77221d to your computer and use it in GitHub Desktop.
Save ttys3/a4786eb2dff87b4e62d1d711da77221d to your computer and use it in GitHub Desktop.
Go doesn't have ternary, so created one...

go-ternary

Yes, I know—yet another attempt at bringing a ternary-like experience to Go. But hey, Go doesn’t have one, and I wasn’t around when the last million were written.

Why?

Because Go doesn't have a ternary operator, and according to the official FAQ, it likely never will. The reasoning? To prevent developers from writing "impenetrably complex expressions." But let's be real—poor coding practices exist in all forms. Instead of outright banning a useful construct, wouldn’t compiler warnings for overly complicated ternary expressions have been a more reasonable approach?

Since that's not happening, here’s go-ternary—because sometimes, a one-liner is just nicer than an if-else.

package ternary
func If[T any](condition bool, ifTrue Supplier[T], ifFalse Supplier[T]) T {
if condition {
return ifTrue.Get()
}
return ifFalse.Get()
}
func Func[T any](supplier func() T) Supplier[T] {
return FuncSupplier[T](supplier)
}
func Value[T any](value T) Supplier[T] {
return ValueSupplier[T]{Value: value}
}
type Supplier[T any] interface {
Get() T
}
type FuncSupplier[T any] func() T
func (s FuncSupplier[T]) Get() T {
return s()
}
type ValueSupplier[T any] struct {
Value T
}
func (s ValueSupplier[T]) Get() T {
return s.Value
}
package ternary
import "testing"
func assertEquals[T comparable](t *testing.T, a T, b T) {
if a != b {
t.Errorf("assertEquals failed: %v != %v", a, b)
}
}
func Test(t *testing.T) {
assertEquals(t, If(true, Value("true"), Value("false")), "true")
assertEquals(t, If(false, Value("true"), Value("false")), "false")
assertEquals(t, If(true, Func(func() string {
return "true"
}), Func(func() string {
t.Error("lazyEvaluate failed: this func should not be called")
return "false"
})), "true")
assertEquals(t, If(false, Func(func() string {
t.Error("lazyEvaluate failed: this func should not be called")
return "true"
}), Func(func() string {
return "false"
})), "false")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment