Golang教程:(六)函数
原文:https://golangbot.com/functions/ 这是本Golang系列教程的第六篇。 函数是完成一个特定任务的代码块。一个函数接受输入,对输入进行一些运算并产生输出。 函数声明在 Go 中声明一个函数的语法为: func functionname(parametername type) returntype {
//function body
}
函数声明以关键字 func 开头,后面是函数名字,接着是在 ( 和 ) 之间指定的参数列表,然后是函数的返回类型。指定参数的语法为参数名称后面跟着参数类型。可以指定任意数量的参数,形式为: 在一个函数中,参数和返回值是可选的。因此下面的语法也是合法的函数声明: 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
}
在上面的函数中,area 和 perimeter 是具名返回值。注意 (译者注:在Go中,有返回值的函数,无论是具名返回值还是普通形式的返回值,函数中必须包含 return 语句。) 空指示符在 Go 中,下划线( 我们知道上面定义的函数 下面的程序仅接收 package main
import (
"fmt"
)
func rectProps(length,width float64) (float64,perimeter
}
func main() {
area,_ := rectProps(10.8, 5.6) // perimeter is discarded
fmt.Printf("Area %f ",area)
}
在 函数的介绍到此结束。感谢阅读。 目录 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |