Closed
Description
I disagree with the Go convention and language's designers arguments here https://golang.org/doc/faq#Does_Go_have_a_ternary_form and think that it is a real missing feature in the language.
Consider in C the following code:
printf("my friend%s", (nbFriends>1?"s":""));
or in C++ :
std::cout << "my friend" << (nbFriends>1?"s":"") << std::endl;
In Go it causes either huges repetitions which can cause mistakes, or very verbose and inefficient code, or both, for something which should be straightforward:
Solution 1:
// horribly repetitive, risk of divergence between the two strings
if nbFriends > 1 {
fmt.Printf("my friends\n")
} else {
fmt.Printf("my friend\n")
}
Solution 2:
// difficult to read
fmt.Printf("my friend")
if nbFriends > 1 { fmt.Printf("s") }
fmt.Printf("\n")
Solution 3:
// difficult to read
var plural = ""
if nbFriends > 1 { plural = "s" }
fmt.Printf("my friend%s\n", plural)
Solution 4:
// dangerous (ifTrue and ifFalse are both evaluated,
// contrary to a real ternary operator),
// and not generic at all (works only for strings)
func ifStr(condition bool, ifTrue string, ifFalse string) string {
if condition {
return ifTrue
}
return ifFalse
}
fmt.Printf("my friend%s\n", ifStr(nbFriends > 1, "s", ""))
Solution 5:
// horrible to read, probably inefficient
fmt.Printf("my friend%s\n",
func(condition bool) string {
if condition {
return "s"
}
return ""
}(nbFriends > 1))