Skip to content

Provides a simple implementation of ternary expressions

Notifications You must be signed in to change notification settings

robtimus/go-ternary

Repository files navigation

go-ternary

Build Status Quality Gate Status Coverage Known Vulnerabilities

A simple implementation of ternary expressions in Go.

The Go language does not support ternary expressions. That means that you have to write quite some boilerplate code to achieve the same:

var result TYPE
if condition {
    result = trueResult
} else {
    result = falseResult
}

This module allows you to do the same with just a single line. To allow Go to infer the generic type, ternary expressions need to be written as in Python: trueResult if condition else falseResult:

result := ternary.Return(trueResult).When(condition).Else(falseResult)

Lazy evaluation

The Return and Else above both require the values to be evaluated eagerly. For constants, pre-existing variables and simple expressions this is fine. However, for more complex expressions it makes more sense to use lazy evaluation. That can be achieved using Call and ElseCall:

result := ternary.Call(func() TYPE { ... }).When(condition).ElseCall(func() TYPE { ... })

It's of course also possible to mix eager and lazy evaluation:

result1 := ternary.Return(trueResult).When(condition).ElseCall(func() TYPE { ... })
result2 := ternary.Call(func() TYPE { ... }).When(condition).Else(falseResult)

About

Provides a simple implementation of ternary expressions

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages