<代码>//main.go code_005_functions项目 主要包 导入( “fmt” ) func Test1 (int, b, c字符串)(str3字符串){ fmt。Printf (" % d % s, % s, a, b, c) 返回字符串(a) + b + c } int func Test2 () { 我:=1 总结:=0 i=1;我& lt;=100;我+ + { 和+=我 } 返回总和 } func Test3 int (num int) {//递归函数的使用 如果num==1 { 返回1 } 返回num + Test3 (num-1) }//函数作为参数传递,我们使用类型来定义//它的类型就是所有拥有相同的参数,相同的返回值的一种类型。 int类型FuncType func (int, int)//func后面没有函数名 int func Calc (a, b, f FuncType)(结果int) { 结果=f (a, b) 返回 } 函数添加(a、b int) int { 返回一个+ b } int func - (a, b) int { 返回一个- b } int func广场()函数(){ var x int int返回func(){//匿名函数 x + +//捕获外部变量 返回x * } } 函数main () {//关键函数,函数名,参数列表,返回值,函数体和返回语句//函数名首字母小写即为私有的,大写即为公众//如果有返回值,那么必须在函数的内部添加返回语句 str1:=Test1(11,“你好”,“世界”) fmt。Println (“\ n”+ str1)//递归函数 总和:=Test3 (100) fmt.Println(总和)//函数作为参数传递 res1:=Calc(10年,20年,添加) 它:=Calc (60, 100 -) fmt.Println (res1) fmt.Println(它)//匿名函数与闭包//所谓闭包就是一个函数”捕获”了和它在同一作用域的其它常量和变量。//这就意味着当闭包被调用的时候,不管在程序什么地方调用,闭包能够使用这些常量或者变量。//它不关心这些捕获了的变量和常量是否已经超出了作用域,所以只有闭包还在使用它,这些变量就还会存在。//在去语言里,所有的匿名函数(语言规范中称之为函数字面量)都是闭包。 str:=" ck_god " 外国游客1:=func(){//方式1: fmt。Printf("哈哈哈,我是% s \ n”, str) } f1 () func(){//方式2:匿名函数 fmt.Println(“不好意思,还是我”) }() 类型FuncType func () var f2 FuncType=f1 f2()//方式3:函数变量接收后调用 v:=func (a、b int)(结果int) { 结果=a + b 返回 }(1,1)//方式4:有参有返回值的匿名函数 fmt。Println (“v=v)//闭包捕获外部变量特点:修改外部变量的值 fmt.Println (“\ n=========\ n”) 我:=10 str2:=" ck_god " func () { 我=100 str="去" fmt。Printf("内部:我=% d, str2=% s \ n”,我,str2) }() fmt。Printf("外部:我=% d, str2=% s \ n”,我,str2)//匿名函数作为返回值 f:=广场() fmt.Println (f ()) fmt.Println (f ()) fmt.Println (f ())//我们看到变量的生命周期不由它的作用域决定:广场返回后,变量x仍然隐式的存在于f中 } 代码>