package main
import"fmt"//函数 变量作用域//定义全局变量var num int = 10//定义函数func testGlobal() {
fmt.Println("Global:", num)}functestGlobal1(){ num :=100//1先在自己函数体中查找 //2函数体中找不到就找外层的全局变量
fmt.Println("Global:", num)}//函数作为参数funcadd(x, y int)int{return x + y}funcclac1(x, y int, op func(int,int)int)int{returnop(x, y)}funcmain(){testGlobal()//外层不能访问到内层函数的内部变量 testGlobal1()//变量i只是在for循环中生效 外层访问不到for语句块中的变量 for i :=0; i <5; i++{
fmt.Println(i)}//函数可以作为变量
abc := testGlobal
fmt.Printf("%T\n", abc)abc()
r1 :=clac1(10,20, add)
fmt.Println(r1)}
package main
import"fmt"//定义一个函数它的返回值是一个函数funca()func(){ name :="alex"returnfunc(){ fmt.Println("hello", name)}}funcb(name string)func(){returnfunc(){ fmt.Println("hello", name)}}//匿名函数funcmain(){func(){ fmt.Println("匿名函数")}()//闭包 = 函数 + 外层变量的引用
r :=a()r()//相当于执行了a函数内部的匿名函数
w :=b("harold")w()