Implementing with 2 string
return values
It could look something like this:
func t(test bool, true1, true2, false1, false2 string) (string, string) {
if test {
return true1, true2
}
return false1, false2
}
Testing it:
a1, a2 := t(false, "hi", "hello", "bye", "goodbye")
fmt.Println(a1, a2)
a1, a2 = t(true, "hi", "hello", "bye", "goodbye")
fmt.Println(a1, a2)
Output (try it on the Go Playground):
bye goodbye
hi hello
Implementing with slice []string
return value
It might be easier to read and work with if we implement it with string
slices: []string
.
func t(test bool, trueVal []string, falseVal []string) []string {
if test {
return trueVal
}
return falseVal
}
Testing it:
trueVal := []string{"hi", "hello"}
falseVal := []string{"bye", "goodbye"}
a := t(false, trueVal, falseVal)
fmt.Println(a)
a = t(true, trueVal, falseVal)
fmt.Println(a)
Output (try it on the Go Playground):
[bye goodbye]
[hi hello]
Implementing with a wrapper struct
return value
You may also choose to create a wrapper struct
to hold an arbitrary number of values (even having arbitrary / different types):
type Pair struct {
v1, v2 string
}
func t(test bool, trueVal Pair, falseVal Pair) Pair {
if test {
return trueVal
}
return falseVal
}
Testing it:
trueVal := Pair{"hi", "hello"}
falseVal := Pair{"bye", "goodbye"}
a := t(false, trueVal, falseVal)
fmt.Println(a)
a = t(true, trueVal, falseVal)
fmt.Println(a)
Output (try it on the Go Playground):
{bye goodbye}
{hi hello}