-
Notifications
You must be signed in to change notification settings - Fork 17.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: cmp: Add Cond[T any](cond bool, ifval, elseval T) T #66062
Comments
This is analogous to a ternary conditional operator, but it evaluates its consequent and alternative values eagerly, which makes it less useful. However, I understand that we're not likely to see such an operator in Go any time soon. |
I'll note that it should be func Cond[T any, B ~bool](cond B, ifval, elseval T) T |
I mean, you can make it lazy if you want: https://go.dev/play/p/D9BDFlGF-Uf |
I don't think it's worthwhile to make it generic over bool types. If it were builtin, sure. Of course, if it were builtin, it should be lazy. |
I disagree. |
That is impressive extends to go through to not write a simpler |
Python's solution: _ = ifval if cond else elseval Skips |
👎 this would be weird magic, currently builtins only cheat about the type system (generics before we had generics and |
I had not seen #36303 before. Looks like the builtin version of this has been rejected. I still think the cmp.Cond version is marginally convenient and fits with the general vibe of package cmp. |
Proposal Details
Recently, #64825 was marked as a likely declined proposal. This is an alternate proposal with a similar goal: to make writing simple, commonly used bool conversions easier. Here is the proposed addition:
I have been using a helper like this in my code since Go 1.18 and I find it convenient to have. The bool conversions mentioned in #64825 would be
cmp.Cond(b, 1, 0)
with this alternative proposal.The text was updated successfully, but these errors were encountered: