导言
- 原文链接: Part 6: Functions
- If translation is not allowed, please leave me in the comment area and I will delete it as soon as possible.
函数
函数是什么?
函数是完成指定任务的代码块。函数一般执行如下操作:
- 接收输入。
- 计算。
- 产生输出结果。
函数声明
在 Go
中,声明函数的句式如下:
func functionname(parametername type) returntype {
//function body
}
函数声明以 关键字func
开头,函数名紧随其后。参数被包裹在 (
和 )
之间,最后是函数返回值。参数的格式是:参数名 参数类型
,例如 (parameter1 type, parameter2 type)
。最后,我们在 {
和 }
之间写函数体。
函数中的参数和返回值都是可选的。因此下面也是一个合法的函数声明。
func functionname() {
}
函数样例
让我们来写一个函数吧。函数功能是:根据产品的单价、产品的数量,通过二者相乘,计算出产品总价。
func calculateBill(price int, no int) int {
var totalPrice = price * no
return totalPrice
}
上面的函数接收 2
个 int
参数 — price
、 no
,通过计算,返回 1
个 int
返回值 — totalPrice
。
如果连续的参数,它们的类型相同,那我们只需在这组参数的最后写上类型,而不用每个都写上。即,在这个例子中,price int, no int
可以写为 price, no int
。因此上面的函数也可以写作:
func calculateBill(price, no int) int {
var totalPrice = price * no
return totalPrice
}
既然已经写好了函数,那我们就来调用它吧。
函数的调用句式是 functionname(parameters)
,即,calculateBill
函数 的调用句式是:
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)
}
运行这个程序,输出如下:
Total price is 540
多返回值
在 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, perimeter := rectProps(10.8, 5.6)
fmt.Printf("Area %f Perimeter %f", area, perimeter)
}
如果函数要返回多个值,那这些返回值必须在 (
和 )
之间指明。
func rectProps(length, width float64)(float64, float64)
表示该函数有 2
个 float64
类型 的参数,还有 2
个 float64
类型 的返回值。
上面的程序输出如下:
Area 60.480000 Perimeter 32.800000
命名返回值
在 Go
语言 中,返回值可以被命名。命名的返回值 可以认为是 函数首行定义的局部变量。
采用命名返回值的方式,rectProps
函数 变为:
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
时,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) // perimeter is discarded
fmt.Printf("Area %f ", area)
}
在第 13
行,因为只需要 area
,所以我们使用 _
接收 perimeter
。通过这种方式,我们可以忽略 perimeter
。
这就是本次的教程了~
祝你早日登上人生巅峰~
原作者留言
优质内容来之不易,您可以通过该 链接 为我捐赠。
最后
感谢原作者的优质内容。
欢迎指出文中的任何错误。