英文:
Can I use single variable for method that returns 2 parameters
问题
我有一个简单的问题 - 在方法返回两个值(val和error)的情况下,我可以使用单值赋值吗?
resp := http.Get("http://www.google.com/")
英文:
I have a simple question - can I use single value assignment while method returns 2 values (val and error)?
resp := http.Get("http://www.google.com/")
答案1
得分: 3
赋值语句左侧的操作数数量必须与函数返回的值的数量相匹配。
你可以使用空白标识符来忽略一个返回值:
resp, _ := http.Get("http://www.google.com/")
像这样忽略错误是不好的做法。
英文:
The number of operands on the left side of the assignment must match the number of values returned by the function.
You can use the blank identifier to ignore a return value:
resp, _ := http.Get("http://www.google.com/")
It's bad practice to ignore errors like this.
答案2
得分: 1
从Go语言规范中:
元组赋值将多值操作的各个元素分配给变量列表。有两种形式。在第一种形式中,右操作数是一个单个的多值表达式,例如函数调用、通道或映射操作,或类型断言。左操作数的操作数数量必须与值的数量相匹配。
例如,如果f是一个返回两个值的函数,
x,y = f()将第一个值分配给x,第二个值分配给y。
空白标识符提供了一种忽略赋值中右侧值的方法:
_ = x // 计算x但忽略它
x,_ = f() // 计算f()但忽略第二个结果值
英文:
From Go language specification :
> A tuple assignment assigns the individual elements of a multi-valued
> operation to a list of variables. There are two forms. In the first,
> the right hand operand is a single multi-valued expression such as a
> function call, a channel or map operation, or a type assertion. The
> number of operands on the left hand side must match the number of
> values.
For instance, if f is a function returning two values,
x, y = f() assigns the first value to x and the second to y.
> The blank identifier provides a way to ignore right-hand side values
> in an assignment:
_ = x // evaluate x but ignore it
x, _ = f() // evaluate f() but ignore second result value
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论