# Golang教程：（六）函数

xiaoxiao2021-02-28  19

# 函数声明

func functionname(parametername type) returntype { //function body }

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 totalPrice := calculateBill(price, no) fmt.Println("Total price is ", totalPrice) }

# 多个返回值

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) }

# 具名返回值

func rectProps(length, width float64)(area, perimeter float64) { area = length * width perimeter = (length + width) * 2 return //no explicit return value }

# 空指示符

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) // perimeter is discarded fmt.Printf("Area %f ", area) }