Go內(nèi)置支持多個返回值。此功能經(jīng)常用于通用的Go中,例如從函數(shù)返回結(jié)果和錯誤值。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.com/go/go_environment.html
此函數(shù)簽名中的(int,int)表示函數(shù)返回2個int類型值。
這里使用從多個賦值的調(diào)用返回2個不同的值。如果只想要返回值的一個子集,請使用空白標(biāo)識符_。
接受可變數(shù)量的參數(shù)是Go函數(shù)的另一個不錯的功能; 在接下來實(shí)例中可以來了解和學(xué)習(xí)。
multiple-return-values.go的完整代碼如下所示 -
package main
import "fmt"
// The `(int, int)` in this function signature shows that
// the function returns 2 `int`s.
func vals() (int, int) {
return 3, 7
}
func main() {
// Here we use the 2 different return values from the
// call with _multiple assignment_.
a, b := vals()
fmt.Println(a)
fmt.Println(b)
// If you only want a subset of the returned values,
// use the blank identifier `_`.
_, c := vals()
fmt.Println(c)
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run multiple-return-values.go
3
7
7