Created
September 30, 2019 16:54
-
-
Save kissgyorgy/b11c459cfea0c296e92b4c80a013469e to your computer and use it in GitHub Desktop.
Ternary operator in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type ternary struct { | |
conditionIsTrue bool | |
trueValue interface{} | |
} | |
func If(condition bool) *ternary { | |
return &ternary{conditionIsTrue: condition} | |
} | |
func (t *ternary) Then(trueValue interface{}) *ternary { | |
if t.conditionIsTrue { | |
t.trueValue = trueValue | |
} | |
return t | |
} | |
func (t *ternary) Else(falseValue interface{}) interface{} { | |
if t.conditionIsTrue { | |
return t.trueValue | |
} else { | |
return falseValue | |
} | |
} | |
func main() { | |
trueValue := If(true).Then("true value").Else("false value") | |
fmt.Println("Result:", trueValue) | |
falseValue := If(false).Then("true value").Else("false value") | |
fmt.Println("Result:", falseValue) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment