golang 基礎(5)函式的返回值
在 go 語言中函式支援多個返回值
func div(a, b int) (int, int){ return a /b , a %b }
我們也可以給函式返回值打上標籤 q, r
func div(a, b int) (q,r int){ return a /b , a %b }
我們可以用兩個變數來接受函式返回值
a, b := div(17,3)
如果我們只想使用一個返回值,也就是 a 而不使用 b,向下面這樣做會在編譯時報錯,go 語言是比較嚴格語言
a, b := div(17,3) fmt.Println(a)
應該修改為,通過 _ 佔位符來忽略掉不使用的變數
a, _ := div(17,3) fmt.Println(a)
到現在為止我想大家都理解了 go 語言的返回多個返回值的用法,那麼實際中如何使用這個呢?我們之前呼叫讀取檔案時候,或開啟檔案時,這些函式通常都會返回兩個返回值例如 file, error ,這一點又讓我想起了 nodejs 中的非同步操作基本也都是這個樣子。
那麼我們來改造一下之前的 eval ,讓這個函式也返回兩個值,其中包括一個錯誤值而不是在函式內部處理錯誤。
func eval(a, b int,op string) (int, error) { switch op { case "+": return a + b, nil case "-": return a - b, nil case "*": return a * b, nil case "/": return a / b, nil default: return 0, fmt.Errorf("unsupported operation: %s" + op) } }
if result, err := eval(3,4, "*"); err != nil{ fmt.Println("Error",err) }else{ fmt.Println(result) }
可以返回一個指標,在 go 中我們將函式 sum 內部區域性變數的 result 的記憶體地址作為返回值。如果有其他語言經驗,這裡會有點疑惑,我們函式中的區域性變數不是和函式都放入執行棧中嗎,這些區域性變數隨著函式執行完畢會被釋放嗎,而在 go 中如果你返回區域性變數的地址,這個變數會升級到堆記憶體。
func sum(values ...int) *int { result := 0 for _, v := range values{ result += v } return &result }
s := sum(1,2,3) fmt.Println("The sum is ", *s)
- 函式返回多個值時可以起名字
- 僅用於非常簡單的函式
- 對於呼叫者沒有區別