【问题标题】:How can I use the result of a multi-value returning function as the argument of another function in Golang if I don't need error handling? [duplicate]如果我不需要错误处理,如何使用多值返回函数的结果作为 Golang 中另一个函数的参数? [复制]
【发布时间】:2018-08-07 12:46:07
【问题描述】:

以下是我想要实现的目标

fmt.Println(string(ioutil.ReadAll(res.Body)))

但这会引发以下错误。

multiple-value ioutil.ReadAll() in single-value context

我知道 ioutil.ReadAll() 返回字节和错误。但是我不想多写一行如下

bytes, _ := ioutil.ReadAll(resp.Body)

如果不关心 Go 中的错误处理,是否可以只将 ioutil.ReadAll() 的结果传递给 fmt.Println()?

【问题讨论】:

  • 你不能。对不起。无需尝试,可撤销。

标签: go


【解决方案1】:

如果你只想要一次,我认为这没有什么意义。但是,如果这是一种常见情况,并且您认为它可以大大提高代码的可读性,请尝试以下操作:

// perhaps, there's a better name for this
func resultToString(b []byte, _ error) string { 
    return string(b)
}

// and later:
fmt.Println(resultToString(ioutil.ReadAll(res.Body)))

不幸的是,这是一个特定于字符串的函数,因此对于任何其他类型,您都需要复制它。

【讨论】:

  • ioutil.ReadAll 实际上返回字节,对吧?所以这意味着我必须为 go 中的所有类型编写类似的函数。
  • @aswinmprabhu []byte 确实,更新了答案。是的,在 Go 获得一些泛型类型之前,您必须为所需的每种类型复制它。
  • 作为意向声明,我还将参数更改为(b []byte, _ error)。下划线表明错误将被忽略
  • @EliasVanOotegem 好点,会更新。
  • 我会非常非常警惕任何抑制如此多错误以至于需要一个助手(或多个助手)来完成的程序。那只是自找麻烦。
猜你喜欢
  • 2018-06-30
  • 2022-01-05
  • 1970-01-01
  • 2018-11-09
  • 2020-06-20
  • 2020-03-14
  • 2019-01-26
  • 1970-01-01
  • 2017-03-27
相关资源
最近更新 更多