就是定义在函数外部的变量,谁都能访问。
1. 函数内定义的变量无法在函数外使用。
2. 如果局部变量和全局变量重名,优先访问局部变量。
使用 type 关键字来定义一个函数类型, 具体格式如下:
type calculation func(int, int) int
上面语句定义了一个 calculation 类型,它是一种函数类型,这种函数接收两个 int 类型的参数并且返回一个 int类型的返回值。
凡是满足这个条件的函数都是 calculation类型的函数,例如:
func add(x, y int) int { return x + y } func sub(x, y int) int { return x - y }
add 和 sub 都能赋值给 calculation类型的变量
var c calculation c = add
我们可以生命函数类型的变量并且为该变量赋值:
func main() { var c calculation // 声明一个calculation类型的变量c c = add // 把add赋值给c fmt.Printf("type of c:%T\n", c) // type of c:main.calculation fmt.Println(c(1, 2)) // 像调用add一样调用c f := add // 将函数add赋值给变量f1 fmt.Printf("type of f:%T\n", f) // type of f:func(int, int) int fmt.Println(f(10, 20)) // 像调用add一样调用f }
原文:https://www.cnblogs.com/zhukaijian/p/12879959.html