# [译] part 6: golang 函数

·  阅读 385

## 函数的声明

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

``````func functionname() {
}
``````

## 示例函数

``````func calculateBill(price int, no int) int {
var totalPrice = price * no
}
``````

``````func calculateBill(price, no int) int {
var totalPrice = price * no
}
``````

``````calculateBill(10, 5)
``````

``````package main

import (
"fmt"
)

func calculateBill(price, no int) int {
var totalPrice = price * no
}
func main() {
price, no := 90, 6
totalPrice := calculateBill(price, no)
fmt.Println("Total price is", totalPrice)
}
``````

Run in playground

``````Total price is 540
``````

## 多个返回值

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

Run in playground

``````Area 60.480000 Perimeter 32.800000
``````

## 命名返回值

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

`area``perimeter`是上述函数中的命名返回值。请注意，函数中的`return`语句没有显式返回任何值。由于`area``perimeter`在函数声明中指定了返回值，因此在遇到`return`语句时会自动从函数返回它们。

## 空白标识符

`_`被称为 Go 中的空白标识符。它可以用来代替任何类型的任何值。让我们看看这个空白标识符的用途是什么。

`rectProps`函数返回矩形的面积和周长。如果我们只需要面积而不想要周长怎么办？这就是`_`发挥作用的地方。

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

Run in playground