Repository navigation
Description
It is often asked why Go does not have a ternary operator. The Go FAQ says,
The if-else form, although longer, is unquestionably clearer. A language needs only one conditional control flow construct.
However, technically Go has a second form of control flow:
func printer(i int) bool {
fmt.Println(i)
return i%2 != 0
}
func main() {
_ = printer(1) && printer(2) && printer(3)
// Output: 1\n2\n
}I believe that many of the usecases that people want a ternary operator for could be covered by adding a ?? operator that is similar to && but instead short-circuit evaluates non-boolean expressions while the resulting value is a zero-value.
For example, these two snippets would be identical:
port := os.Getenv("PORT")
if port == "" {
port = DefaultPort
}port := os.Getenv("PORT") ?? DefaultPort
Another use case might be
func New(c http.Client) *APIClient {
return &APIClient{ c ?? http.DefaultClient }
}
In general, ?? would be very useful for setting default values with less boilerplate.
Another use for ?? might be
func write() (err error) {
// ...
defer func() {
closeerr := w.Close()
err = err ?? closeerr
}()
_, err = w.Write(b)
// ...
}
Some rules: ?? should only work if all expressions evaluate to the same type (as is the case for other operators), and ?? should not work for boolean types, since that would cause confusion in the case of a pointer to a bool. If/when Go gets generics, you can trivially write first(ts ...T) T, so the operator is only worth adding to the language if it has short-circuit evaluation.
In summary, ternary is notoriously unclear, but ?? would not be any more unclear than &&. I believe it would be more clear than an equivalent if-statement since it would more clearly express the intent of setting a default, non-zero value.
Activity
randall77 commentedon Feb 11, 2020
None of your examples require the short-circuit behavior. I.e.,
first(ts ...T) Twould work fine for them.earthboundkid commentedon Feb 11, 2020
Yes, that's fair, although so far generics are still only theoretical.
ianlancetaylor commentedon Feb 12, 2020
For language change proposals, please fill out the template at https://go.googlesource.com/proposal/+/refs/heads/master/go2-language-changes.md .
When you are done, please reply to the issue with
@gopherbotpleaseremovelabelWaitingForInfo.Thanks!
earthboundkid commentedon Feb 12, 2020
Intermediate/advanced. Long-time Go user, but not a language dev.
Extensive Python, JavaScript, and PHP. Scattered others.
Incrementally harder, since there would be one more operator to learn, but the operator has syntax and semantics similar to the existing
&&operator, so not as bad as a entirely new language feature.Not AFAICT, but ternary operators are frequently proposed.
Rather than creating a full-blown ternary, it only allows the equivalent of (x != 0) ? x : y or || in languages that have weak-typing of booleans.
It helps anyone who has to write or read default configuration. It helps writers because
??is shorter. It helps readers because an if-statement can do anything, but??is really only useful for setting non-default values, so there's less thinking needed to absorb the meaning of the code.Add
??as an operator. First??evaluates its LHS. If LHS != the zero value for the type, it returns that value. If LHS == the zero value, it also evaluates RHS and returns that value.After the "Logical operators" section, there would be a section "Coalescing operator" with text like:
In the spec,
binary_op = "||" | "&&" | rel_op | add_op | mul_op .would change tobinary_op = "??" | "||" | "&&" | rel_op | add_op | mul_op .In the operator precedence table,2 &&would change to2 && ??. (x ?? y && zwould be disallowed by the type system, so the exact precedence shouldn't matter.)Go provides a convenient way to select the first non-zero value in a series. For example
name := input ?? "Anonymous"means if input is not blank, setnameto it, otherwise use "Anonymous". If the right hand expression is a function, it will only be called if the left hand expression is a zero-value. For example,name := input ?? get_name()will only callget_nameifinputis"".Yes.
Before:
After:
Before:
After:
The costs are that the
??would be unavailable for other uses, and learners of Go would have to learn one more operator. Fortunately, this operator is quite similar to the nullish coalescing operator in C#, PHP, and JavaScript, and theoroperator in Python, so it would be familiar to many learners.The language grammar would change, so essentially every tool would need to learn the new grammar. :-(
Should be negibile.
Negibile.
See spec changes above.
No.
See above.
While it could be abused for control flow, I don't see that as being very likely, since
&&has the same potential today but is not widely used for control flow.No.
It has minor effects on the case of wanting to return the first non-nil error in a write and flush operation:
No, but if there were generics, a user could write a non-shortcircuiting
first(ts ...T) Tfunction instead of using this operator.@gopherbot please remove label WaitingForInfo.
alanfo commentedon Feb 13, 2020
Although I'm a supporter of adding some sort of short-circuiting ternary operator or built-in function to Go, I'm not convinced that this proposal goes far enough in that direction to be worth doing.
If I'm understanding it correctly, what you're proposing is that
??, which is known as the null-coalescing operator in C# and has counterparts in several other languages, would in effect become a 'zero value' coalescing operator in Go.So stuff like this would become possible:
As such it's equivalent to writing the following in a C-like pseudo-code:
This is really quite limited compared to a 'full-fat' ternary operator where the condition can be any boolean expression. So, whilst I congratulate you on a novel proposal, I'm finding it difficult to get enthused about it.
deanveloper commentedon Feb 13, 2020
Note that this is similar to
||, not&&in JavaScript and similar weakly-typed languages.&&means "if the left side is true, evaluate to the right side" while||means "if the left side is false, evaluate to the right side".Many languages have similar concepts and are widely used, however I don't see the use as much in Go. Go relies less on classical sentinel values than other languages, and instead uses errors to denote when errors happen, rather than returning a sentinel value.
It still does have it's uses of course as you've shown, but I still think coalescing is a bit limited in the context of Go.
earthboundkid commentedon Feb 13, 2020
Yes, exactly. :-)
I believe this covers a huge amount of the situations where ternary is actually useful without allowing the complexity of ternary that the Go authors specifically don't want.
Your examples use single letters, so it makes the
??operator seem pointless, but in real code, these sorts of things come up all the time:etc.
earthboundkid commentedon Feb 13, 2020
Yes, thanks for pointing that out. I realized that I had written the wrong thing before when I was writing up the change proposal template but didn't go back and correct it.
infeno commentedon Feb 13, 2020
For future proof (if this is the right scenario), we should avoid
??. I’m a beginner in Go but I can see major issue in this proposal.I have often assume empty string/out of range/garbage value as either valid or not valid, how can we be sure the user supply value/input is correct?
Invalid value could also cause runtime errors that I prefer to stick to the current way to handle such cases with regexp or custom validations in a function that can be change without breaking change and less noise.
In my opinion, I would wish to avoid less boilerplate for this case. I guess it was possible for JavaScript and PHP as they are scripting languages that can benefits from smaller file size transfer over the slow connectivity and seem fragile for Go, and opportunity to make an assumption that it work in my specifications/requirements.
I see Github CLI as one of an example:
https://github.com/cli/cli
27 remaining items
jimmyfrasche commentedon Jun 4, 2023
I would presume that nothing else changes.
earthboundkid commentedon Jun 4, 2023
If a b and c are all eg strings, I would want (a && b) == c, but if a is a bool and b c are strings, I want a && (b == c).
kurahaupo commentedon Jun 4, 2023
rsc commentedon Jun 21, 2023
Marking this obsoleted by #60204.
rsc commentedon Jun 21, 2023
This proposal has been declined as obsolete.
— rsc for the proposal review group
kurahaupo commentedon Jun 22, 2023
@rsc
This proposal would appear to be significantly broader than #60204:
stringSo I am unclear why "obsoleted by" wasn't in the opposite direction.
If there are other reasons to decline this proposal, could we have some feedback on them please?
earthboundkid commentedon Jun 22, 2023
I think using || would be confusing because of type issues like #60933, and using ?? is a big change because it introduces a new operator. I hope that #26842 does get approved some day though.
ianlancetaylor commentedon Jun 23, 2023
@kurahaupo
True.
#60204 applies to any comparable type, not just string.
In the Go world that is a minor advantage.
Adding a new operator is a language change that has a much much higher bar than adding a new function to the standard library. Supporting short-circuit evaluation simply isn't a strong enough argument for adding an operator. Sorry.