drqja5919276 2019-02-01 16:02
浏览 107
已采纳

Go中允许省略可选的第二个返回值的案例列表

When calling functions or methods with multiple return values, the caller, if unpacking any return values, must unpack them ALL.

f, err := os.Open("filename")

The err variable must be either declared or ignored with the blank identifier _, but it cannot be omitted.

However, there are some operations built into the language, which allow one to omit the optional second return value.

Is there a more or less formal list of situations where an operation with a data structure or a function call returns a second value that is optional and can be ignored by only receiving the first return value? For example:

m := make(map[string]int)
v, ok := m["hello"]

The ok variable is entirely optional and can be omitted.

v := m["hello"]

Likewise, with channels:

v, ok := <-ch

or

v := <-ch

Are there any other cases of that behavior beyond the two above?

  • 写回答

1条回答 默认 最新

  • dongyukang7006 2019-02-01 16:08
    关注

    The expressions with optional values when used in an assignment or initialization are: type assertion, map index and channel receive.

    The specification does not have a formal list of these expressions, but the expressions are all described in the specification.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料