避免使用与返回2值的函数一起嵌套? [英] Avoid nesting from conjunction with function that returns 2 values in go?

查看:120
本文介绍了避免使用与返回2值的函数一起嵌套?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里,我有一个包含一些返回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()
}

请注意,这相当于原始代码,因为&& 运算符是从左到右计算的,它使用短路评估:如果任何操作数的评估结果为 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
}


Here, I have a conjunction expression involving some functions that return 2 values:

if _, ok := f(); ok {
  if _, ok := g(); !ok {
    if h() {
      if _, ok := i(); ok {
        doStuff()
      }
    }
  }
}

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 bool return value, e.g.:

func check(dummy interface{}, ok bool) bool {
    return ok
}

And using it:

if check(f()) && check(g()) && h() && check(i()) {
    doStuff()
}

Note that this is equivalent to the original code because the && 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.

This 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{}).

This is covered in the Spec: Calls:

As a special case, if the return values of a function or method 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.

Note: since the first parameter in 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
}

这篇关于避免使用与返回2值的函数一起嵌套?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆