func functionname(parametername type) returntype { // 函數體(具體實現的功能) }
函數中的參數列表和返回值並非是必須的,所以下面這個函數的聲明也是有效的
func functionname() { // 譯注: 表示這個函數不需要輸入參數,且沒有返回值 }
func calculateBill(price int, no int) int { var totalPrice = price * no // 商品總價 = 商品單價 * 數量 return totalPrice // 返回總價 }
func calculateBill(price, no int) int { var totalPrice = price * no return totalPrice }
calculateBill(10, 5)
完成了示例函數聲明和調用后,我們就能寫出一個完整的程序,並把商品總價打印在控制台上:
package main import ( "fmt" ) func calculateBill(price, no int) int { var totalPrice = price * no return totalPrice } func main() { price, no := 90, 6 // 定義 price 和 no,默認類型為 int totalPrice := calculateBill(price, no) fmt.Println("Total price is", totalPrice) // 打印到控制台上 }
該程序在控制台上打印的結果為
Total price is 540
Go 語言支持一個函數可以有多個返回值。我們來寫個以矩形的長和寬為輸入參數,計算並返回矩形面積和周長的函數 rectProps。矩形的面積是長度和寬度的乘積, 周長是長度和寬度之和的兩倍。即:
-
面積 = 長 * 寬
-
周長 = 2 * ( 長 + 寬 )
package main import ( "fmt" ) func rectProps(length, width float64)(float64, float64) { var area = length * width var perimeter = (length + width) * 2 return area, perimeter } func main() { area, perimeter := rectProps(10.8, 5.6) fmt.Printf("Area %f Perimeter %f", area, perimeter) }
Area 60.480000 Perimeter 32.800000
從函數中可以返回一個命名值。一旦命名了返回值,可以認為這些值在函數第一行就被聲明為變量了。
上面的 rectProps 函數也可用這個方式寫成:
func rectProps(length, width float64)(area, perimeter float64) { area = length * width perimeter = (length + width) * 2 return // 不需要明確指定返回值,默認返回 area, perimeter 的值 }
在 Go 中被用作空白符,可以用作表示任何類型的任何值。
我們繼續以 rectProps 函數為例,該函數計算的是面積和周長。假使我們只需要計算面積,而並不關心周長的計算結果,該怎么調用這個函數呢?這時,空白符 _ 就上場了。
下面的程序我們只用到了函數 rectProps 的一個返回值 area
package main import ( "fmt" ) func rectProps(length, width float64) (float64, float64) { var area = length * width var perimeter = (length + width) * 2 return area, perimeter } func main() { area, _ := rectProps(10.8, 5.6) // 返回值周長被丟棄 fmt.Printf("Area %f ", area) }