函数
Q7nl1s admin

什么是函数?

函数是执行特定任务的代码块。函数接受输入,对输入执行一些计算,然后生成输出。

函数声明

在 go 中声明函数的语法是:

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

函数声明以func关键字开头,后跟functionname. 参数在函数的()之间后面指定returntype。指定参数的语法是参数名称后跟类型。可以指定任意数量的参数,例如(parameter1 type, parameter2 type). 然后在{}之间有一段代码,它是函数的主体。

参数和返回类型在函数中是可选的。因此,以下语法也是有效的函数声明。

1
2
func functionname() {  
}

示例函数

让我们编写一个函数,将单个产品的价格和产品数量作为输入参数,并通过将这两个值相乘来计算总价格并返回输出。

1
2
3
4
func calculateBill(price int,no int) int {
var totalPrice = price * no
return totalPrice
}

上面的函数有两个int 类型的输入参数price,它返回 priceno 的乘积。返回值totalPrice也是 int 类型。

**如果连续的参数类型相同,我们可以避免每次都写类型,最后写一次就够了。即price int, no int可以写成price, no int**。因此,上述函数可以重写为:

1
2
3
4
func calculateBill(price int,no int) int {
var totalPrice = price * no
return totalPrice
}

现在我们已经准备好了一个函数,让我们从代码中的某个地方调用它。调用函数的语法是functionname(parameters). 上面的函数可以使用代码调用。

1
calculateBill(10, 5)  

这是使用上述功能并打印总价的完整程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)
}

上面的程序将打印

1
Total price is 540  

多个返回值

一个函数可以返回多个值。让我们编写一个函数rectProps,它接受一个矩形的lengthwidth并返回矩形的areaperimeter。长方形的面积是长宽的乘积,周长是长宽之和的两倍。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.88,5.6)
fmt.Println("Area %f Perimeter %f",area,perimeter)
}

如果一个函数返回多个返回值,那么它们必须在()之间指定。func rectProps(length, width float64)(float64, float64)有两个 float64 参数length and width,也返回两个float64值。上面的程序打印

1
Area 60.480000 Perimeter 32.800000  

命名返回值

可以从函数返回命名值。如果返回值被命名,则可以认为它在函数的第一行被声明为变量。

上面的 rectProps 可以使用命名的返回值重写为

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

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

空白标识符

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

rectProps函数返回矩形的面积和周长。如果我们只需要area并且想要丢弃perimeter. 这是_有用的地方。

下面的程序仅使用rectProps值函数返回area的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,_:= recctProps(10.8,5.6) // perimeter is discarded
fmt.Println("Area %f",area)
}

在第13行我们只需要area所以_标识符用来丢弃perimeter.

 Comments
Comment plugin failed to load
Loading comment plugin
Powered by Hexo & Theme Keep
Unique Visitor Page View