避免使用与返回2值的函数一起嵌套? [英] Avoid nesting from conjunction with function that returns 2 values in go?
问题描述
这里,我有一个包含一些返回2个值的函数的连接表达式:
if _,ok:= f ); OK {
if _,ok:= g(); !ok {
if h(){
if _,ok:= i(); OK {
doStuff()
}
}
}
}
我可以以某种方式避免嵌套吗?而不是嵌套,我可以把它作为一个表达式写在一行中(在这种情况下,我不能完全断开或返回)?
使用助手函数,您可以。
创建一个帮助器函数,它返回第二个 bool
return值,例如:
pre $ func check(dummy interface {},ok bool)bool {
return ok
}
使用它:
if check(f())&&检查(g())&& h()&& check(i()){
doStuff()
}
请注意,这相当于原始代码,因为 这个 这在规范:致电: 作为一种特殊情况,如果函数或方法的返回值 注意:由于 Here, I have a conjunction expression involving some functions that return 2 values: Could I somehow avoid the nesting? Instead of nesting, could I write this as an expression in one line (I can't quite break or return early in this case)? With a helper function, you can. Create a helper function which returns the second And using it: Note that this is equivalent to the original code because the This This is covered in the Spec: Calls: As a special case, if the return values of a function or method Note: since the first parameter in
这篇关于避免使用与返回2值的函数一起嵌套?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!&&
运算符是从左到右计算的,它使用短路评估:如果任何操作数的评估结果为 false ,则其他操作数(函数)不会被调用。
$ b check()
函数适用于返回2个值的所有函数,第二个类型为 bool
(因为任何值都可以分配给 interface {}
类型的变量)。
$ b
g
在数量上相等,可单独分配给另一个函数或方法的参数 f
,那么调用 f(g(parameters_of_g))
会调用 f $将
g
的返回值按顺序绑定到 f
的参数之后的c $ c>。 f
的调用除了调用 g
和 g
必须至少有一个返回值。如果 f
具有最终的 ...
参数,则会为其分配返回值 g
check()
没有被使用,我们甚至可以在命名时使用空白标识符,这会使我们显然不使用该参数:
func check(_ interface {},ok bool)bool {
return ok
}
if _, ok := f(); ok {
if _, ok := g(); !ok {
if h() {
if _, ok := i(); ok {
doStuff()
}
}
}
}
bool
return value, e.g.:func check(dummy interface{}, ok bool) bool {
return ok
}
if check(f()) && check(g()) && h() && check(i()) {
doStuff()
}
&&
operator is evaluated from left to right and it is using short-circuit evaluation: if any of the operands evaluate to false
, further operands (functions) will not be called.check()
function works for all functions that return 2 values and the 2nd is of type bool
(because any value can be assigned to a variable of type interface{}
).
g
are equal in number and individually assignable to the parameters of another function or method f
, then the call f(g(parameters_of_g))
will invoke f
after binding the return values of g
to the parameters of f
in order. The call of f
must contain no parameters other than the call of g
, and g
must have at least one return value. If f
has a final ...
parameter, it is assigned the return values of g
that remain after assignment of regular parameters.check()
is not used, we can even use the blank identifier when naming it which will make it obvious that we don't use that parameter:func check(_ interface{}, ok bool) bool {
return ok
}