-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Open
Description
Proposal Details
Related to #60204 - I find cmp.Or very useful, although I would appreciate a variant which does not 'execute' the inputs to subsequent parameters.
I propose a variant of this function, which itself takes in a variable number of functions, and executes each until one of them returns a non-zero result.
The motivation for this is to provide behaviour similar to connect() || die('ohnoes') in Perl, Ruby, etc. So, each parameter is like a 'fallback' of the previous parameter. It should only be executed if the previous parameter(s) returned zero.
// OrFunc returns the the return-value of the first argument (a function), that is not equal to the zero value.
// If no argument is non-zero, it returns the zero value.
// OrFunc is inspired by Or and Perl's`||` operator
func OrFunc[T comparable, F func() T](funcs ...F) T {
var zero T
for _, f := range funcs {
t := f()
if t != zero {
return t
}
}
return zero
}See here for a working example: https://go.dev/play/p/GYr6qeT7pDg
Thanks!
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Incoming