函数

什么是函数

函数是用来完成某个任务的代码块。一个函数接收一组输入,根据输入执行一些计算,然后产生一个输出。

函数声明

函数声明的语法如下:

func functionname(parameter type) returntype {
    // 函数体
}

首先是关键字func,接着是函数名称functionname,然后是函数的参数列表,参数列表由小括号括起来,然后是函数的返回值类型returntype,最后一对大括号括起来的函数体。参数列表可以添加多个参数:(parameter1 type, parameter2 type)

函数的参数列表和返回值类型是可选的,因此下面的写法也是合法的:

func functionname() {
}

函数举例

我们现在来实现一个简单的计算价钱的函数,该函数接收两个参数,商品单价和商品数量,将二者相乘即可算出总的价钱。

func calculateBill(price int, no int) {
    totalPrice := price *no
    return totalPrice
}

该函数接收两个参数priceno,均为int类型,返回值类型也是int

如果连续几个参数是相同的数据类型,那么可以仅在最后一个参数名称后面声明数据类型,没必要每个参数都写一遍。比如price int, no int可以简写为price, no int。因此上面的函数可以简写为:

func calculateBill(price, no int) int {
    totalPrice := price *no
    return totalPrice
}

函数定义好之后我们就可以在其他地方调用了。函数调用语法如下:functionname(parameters)。一般把函数声明时的参数称为形参,函数调用时的参数称为实参。前面定义的函数可以这样调用:

calculateBill(10, 5)

前面的函数完整的声明与调用实现如下:

package main

import (  
    "fmt"
)

func calculateBill(price, no int) int {  
    totalPrice := price * no
    return totalPrice
}

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

Go Playground在线运行

执行结果如下:

Total price is 540

多个返回值

Golang中一个函数可以有多个返回值。现在我们实现一个函数rectProps,接收参数为矩形的长和宽,返回两个计算结果,矩形的面积(长度乘以宽度)和矩形的周长(长度加上宽度再乘以2)。

package main

import (
    "fmt"
)

func rectProps(length, width float64) (float64, float64) {
    area := length *width
    perimeter := (length +width) * 2
    return area, perimeter
}

func main() {
    area, perimeter := rectProps(10.8, 5.6)
    fmt.Printf("Area %f Perimeter %f", area, perimeter)
}

Go Playground在线运行

如果函数返回值为多个,那么返回值类型需要用小括号扩起来(float64, float64)。 该程序执行结果如下:

Area 60.480000 Perimeter 32.800000

_ 占位标识符

Golang中我们一般称_为占位标识符。_可用来占位任何类型的任何值。现在看下怎么使用占位标识符。

前面定义的函数rectProps有两个返回值:面积area和周长perimeter。如果我们仅仅需要area,而用不着perimeter,这时占位标识符就派上用场了。

package main

import (
    "fmt"
)

func rectProps(length, width float64) (float64, float64) {
    area := length *width
    perimeter := (length +width) * 2
    return area, perimeter
}

func main() {
    area, _ := rectProps(10.8, 5.6)
    fmt.Printf("Area %f", area)
}

Go Playground在线运行 这里我们使用占位标识符_将第二个函数返回值显示丢掉不用,如果这里我们声明一个周长变量或者直接省略第二个返回值,则都会报错,可见Golang是一门严谨而且优雅的编程语言。

Last updated