Duplicate of#36303
Description
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:
func Cond[T any](cond bool, ifval, elseval T) T {
if cond {
return ifval
}
return elseval
}
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.
Metadata
Metadata
Assignees
Type
Projects
Status
Incoming
Milestone
Relationships
Development
No branches or pull requests
Activity
seh commentedon Mar 1, 2024
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.
Merovius commentedon Mar 1, 2024
I'll note that it should be
x0wllaar commentedon Mar 1, 2024
I mean, you can make it lazy if you want: https://go.dev/play/p/D9BDFlGF-Uf
earthboundkid commentedon Mar 1, 2024
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.
Merovius commentedon Mar 1, 2024
I disagree.
bool
is a declared type and it would be pretty frustrating, having to convert it if you happen to use a user-declared boolean type (this is different for slices, for example, wheretype MySlice []T
is assignable to[]T
). Not that declaring boolean types is incredibly common, but it's not unheard of. And the cost seems close to zero. For a standard library function, it seems like a no-brainer to me, that we'd want to make it as general as we can.Jorropo commentedon Mar 2, 2024
That is impressive extends to go through to not write a simpler
if
check.zigo101 commentedon Mar 2, 2024
#36303 proposal: new builtin to pick from one of two values
#37739 proposal: Go 2: lazy values
Zig's solution:
Jorropo commentedon Mar 2, 2024
Python's solution:
Skips
()
but is not intuitive (it's forced by parser limitations and falls out of the requirements but it's still weird).Jorropo commentedon Mar 2, 2024
👎 this would be weird magic, currently builtins only cheat about the type system (generics before we had generics and
~string
→~[]byte
signature overload) but not control flow. The value of adding control flow cheats so you can save a couple of ⏎ presses is low to me.earthboundkid commentedon Mar 2, 2024
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.