https://github.com/robtimus/go-ternary
Provides a simple implementation of ternary expressions
https://github.com/robtimus/go-ternary
golang ternary ternary-expression
Last synced: 2 months ago
JSON representation
Provides a simple implementation of ternary expressions
- Host: GitHub
- URL: https://github.com/robtimus/go-ternary
- Owner: robtimus
- Created: 2024-08-29T11:41:31.000Z (9 months ago)
- Default Branch: master
- Last Pushed: 2025-02-28T20:06:37.000Z (3 months ago)
- Last Synced: 2025-02-28T22:59:20.842Z (3 months ago)
- Topics: golang, ternary, ternary-expression
- Language: Go
- Homepage:
- Size: 6.84 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-ternary
[](https://github.com/robtimus/go-ternary/actions/workflows/build.yml)
[](https://sonarcloud.io/summary/overall?id=robtimus%3Ago-ternary)
[](https://sonarcloud.io/summary/overall?id=robtimus%3Ago-ternary)
[](https://snyk.io/test/github/robtimus/go-ternary)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:
```go
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`:
```go
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`:
```go
result := ternary.Call(func() TYPE { ... }).When(condition).ElseCall(func() TYPE { ... })
```It's of course also possible to mix eager and lazy evaluation:
```go
result1 := ternary.Return(trueResult).When(condition).ElseCall(func() TYPE { ... })
result2 := ternary.Call(func() TYPE { ... }).When(condition).Else(falseResult)
```