You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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`||` operatorfuncOrFunc[Tcomparable, Ffunc() T](funcs...F) T {
varzeroTfor_, f:=rangefuncs {
t:=f()
ift!=zero {
returnt
}
}
returnzero
}
Regardless of whether we add that function to the library, it should not be called And, as it is not the dual of Or due to the lazy or "short-circuit" behavior. An And that is the strict dual seems like a reasonable function, so we shouldn't foreclose adding it later, even if there seems to be little need.
How often does this need really arise? The resulting code isn't especially pretty, compared to, say, a single function containing an if-else chain of return statements.
I don't think this makes sense in a world without short function literals (#21498). Even with short function literals, it's not clear that this is better than an if-else chain.
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) returnedzero
.See here for a working example: https://go.dev/play/p/GYr6qeT7pDg
Thanks!
The text was updated successfully, but these errors were encountered: