从没有中间变量的多上下文函数调用中获取单个结果

时间:2016-05-02 21:25:47

标签: go

Go中,我可以使用underscore忽略返回多个值的函数的返回值。例如:

res, _ := strconv.Atoi("64")

假设我想将第一个值直接用于另一个函数调用(在此示例中忽略错误检查最佳实践):

myArray := make([]int, strconv.Atoi("64"))

编译器会抱怨我在单值上下文中使用了多值函数:

./array-test.go:11: multiple-value strconv.Atoi() in single-value context

是否可以从单行返回值中“选择”而不诉诸auxiliary functions

1 个答案:

答案 0 :(得分:1)

唯一真正的方法是创建一些实用工具"绕过"函数,因为这是Go,你必须为每个类型声明一个。

例如:

func noerrInt(i int, e err) int {
   return i
}

然后你可以这样做:

myArray := make([]int, noerrInt(strconv.Atoi("64")))

但实际上,这非常糟糕,并且忽略了最佳实践。