https://github.com/mileusna/conditional
Package conditional is go/golang replacement for ternary if/else operator
https://github.com/mileusna/conditional
condition conditional conditional-statements conditions go golang ifelse ternary
Last synced: 21 days ago
JSON representation
Package conditional is go/golang replacement for ternary if/else operator
- Host: GitHub
- URL: https://github.com/mileusna/conditional
- Owner: mileusna
- License: mit
- Created: 2017-07-17T18:37:12.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2020-08-07T20:14:30.000Z (almost 6 years ago)
- Last Synced: 2024-06-21T18:13:01.386Z (almost 2 years ago)
- Topics: condition, conditional, conditional-statements, conditions, go, golang, ifelse, ternary
- Language: Go
- Homepage:
- Size: 4.88 KB
- Stars: 8
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Go/Golang replacement for ternary if/else operator [](https://godoc.org/github.com/mileusna/conditional)
Package conditinal is go/golang replacement for ternary if/else operator
Many languages have ternary operator which makes it easy and short to assign value inline, for example
```
// pseudocode, not the go code :(
val := (x==y) ? "Value OK" : "Value not OK"
```
Unfortunately, [there is no ternary testing operator in Go](https://golang.org/doc/faq#Does_Go_have_a_ternary_form) so the shortest way to write this code in go would be
```Go
val := "Value not OK"
if x==y {
val = "Value OK"
}
```
or if you prefere perhapse more readable but longer version
```Go
var val string
if x==y {
val = "Value OK"
} else {
val = "Value not OK"
}
```
This is where conditional package steps in. It provides fuctions that replaces ternary operator for each basic type in go. We can now write conditional assignment in only one Go line:
```Go
val := conditional.String(x==y, "Value OK", "Value not OK")
```
Package conditional also provides fuctions for all Go basic types
```Go
n := conditional.Int(x==y, 20, 0)
u := conditional.UInt(true, 23, 15)
f := conditional.Float64(true, 23.2, 15.1)
// etc. etc.
// even for interface{}
i := conditional.Interface(x==y, "Great", 10)
```
Example:
```Go
package main
import (
"fmt"
"github.com/mileusna/conditional"
)
func main() {
x := 2
y := 3
fmt.Println(conditional.Int(x==y, 20, 0))
fmt.Println(conditional.String(x==y, "Value OK", "Value not OK"))
fmt.Println(conditional.UInt(true, 23, 15))
fmt.Println(conditional.Float64(true, 23.4, 15.1))
}
```