英文:
Use one return value?
问题
我想调用我的函数test并使用其中一个返回值。我该如何说“给我第一个或第二个值”?我以为下面的代码会给我“one”,但是[1]
是错误的用法,导致编译错误。
package main
import (
"fmt"
)
func test() (int, string) { return 1, "one"; }
func main() {
i, sz := test()
fmt.Printf("%d=%s\n", i, sz)
fmt.Printf("%s", test()[1]) //error
}
英文:
I want to call my function test and use one of the return values. How do I say give me the first or second value? I thought the below would give me "one" but [1]
is incorrect usage causing a compile error
package main
import (
"fmt"
)
func test() (int, string) { return 1, "one"; }
func main() {
i,sz:=test()
fmt.Printf("%d=%s\n",i,sz)
fmt.Printf("%s", test()[1]) //error
}
答案1
得分: 4
据我所知,您无法对函数返回值进行下标操作。您可以这样做:
_, someString := test();
fmt.Println(someString);
英文:
As far as I know, you can't subscript function return values. You can do:
_, someString := test();
fmt.Println(someString);
答案2
得分: 3
引用Go语言规范:
形式为
a[x]
的主表达式表示由x索引的数组、切片、字符串或映射a的元素。值x分别称为索引或映射键。[...] 否则(如果a不是数组、切片、字符串或映射),a[x]
是非法的。
然而,在Go语言中,多个返回值并不是返回的数组,而是一种独立的语言特性。这是必须的,因为数组只能保存单一类型的元素,而返回值可以是不同类型的。
但是由于返回值不是数组(或切片、字符串或映射),根据语言规范,a[x]
的语法是错误的。因此,正如@dav已经正确指出的那样,你必须将返回值实际分配给一个变量,以便在其他地方使用它。
在特殊情况下,你可以利用这个小技巧来避免变量赋值:
作为一个特例,如果函数或方法g的返回值与另一个函数或方法f的参数数量相等,并且可以逐个赋值给f的参数,则调用f(g(g的参数))将按顺序将g的返回值绑定到f的参数后调用f。
这使得以下操作成为可能:
func foo() (int, string) {
return 42, "test";
}
func bar(x int, s string) {
fmt.Println("Int: ", x);
fmt.Println("String: ", s);
}
func main() {
bar(foo())
}
英文:
Citing the Go Language Specification:
> A primary expression of the form a[x]
denotes the element of the array, slice, string or map a indexed by x. The value x is called the index or map key, respectively. [...] Otherwise [if a is not an array, slice string or map] a[x] is illegal.
Multiple return values in Go, however, are not arrays being returned, but a separate language feature. This must be so, because an array can only hold elements of a single type, but return values can be of different types.
But since return values are not arrays (or slices, strings or maps), the a[x]
syntax is, per language spec, a syntax error. As a result, as @dav has already correctly stated, you will have to actually assign the return value to a variable in order to use it elsewhere.
In special cases, you may be able to use this bit of trivia to avoid variable assignment:
> 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.
Which makes the following possible:
func foo() (int, string) {
return 42, "test";
}
func bar(x int, s string) {
fmt.Println("Int: ", x);
fmt.Println("String: ", s);
}
func main() {
bar(foo())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论