标准的函数写法
参数 参数类型 返回的类型
func getSum(n1 int, n2 int) int{
sum := n1 + n2
return sum
}
func main(){
res := getSum(1, 2)
fmt.Println(res)
}
实参:给函数实际传递的参数,例如上面的1,2
形参:形式上的参数,例如上面的n1和n2
返回值
golang函数支持返回多个返回值
func getRes(n1 int, n2 int) (int, int) {
sum := n1 + n2
difference := n1 - n2
return sum, difference
}
两个及以上的返回值,上面类型要加括号
返回值命名
func getRes(n1, n2 int) (sum, difference int) {
sum = n1 + n2
difference = n1 - n2
return
}
函数也是一种数据类型
函数不是变量,但他也存在与内存中,存在内存地址
函数名的本质就是一个指向其函数内存地址的指针常量
func getRes(n1, n2 int) (sum, difference int) {
sum = n1 + n2
difference = n1 - n2
return
}
func main() {
fmt.Printf("getRes is %v, type is %T", getRes, getRes)
//getRes is 0x4aca00, type is func(int, int) (int, int)
}
所以,我们也可以以声明变量的形式声明函数
var getRes = func(n1, n2 int) (sum, difference int) {
sum = n1 + n2
difference = n1 - n2
return
}
a, b := getRes(1, 2)
fmt.Println(a, b)
getRes 对应的那个函数也叫匿名函数
立即调用的匿名函数
a, b := func(n1, n2 int) (sum, difference int) {
sum = n1 + n2
difference = n1 - n2
return
}(1, 2)
fmt.Println(a, b)