Code_005_functions Project Main.gopackage mainimport ("FMT") func Test1 (a int, B, c string) (Str3 string) {fmt. Printf ("%d,%s,%s", A, B, c) return string (a) + B + c}func Test2 () int {i: = 1 sum: = 0 for i = 1; I <=; i++ {su M + = i} return sum}func Test3 (num int) int {////recursive function using if num = = 1 {return 1} return num + Test3 (num-1)}//function as parameter passing, we use Type to define//It is a type that has all the same parameters, the same return value. Type functype func (int, int) int//func no function name Func Calc (A, b int, F functype) (result int) {result = f (A, B) return}func Add (A, b int) int {return a + B}func minus (A, b int) int {return a-b}func squares () func () int {var x int return func () int {//anonymous function X + +//capture external variable return x * x}}func Main () {//key func, function name, parameter list, return value, function body and return statement//function name lowercase is private, uppercase is public// If there is a return value, you must add the return statement inside the function str1: = Test1 (11, "Hello", "World") fmt. Println ("\ n" + str1)//recursive function sum: = TEST3 (+) fmt. The PRINTLN (sum)//function is passed as a parameter res1: = Calc (ten, Add) Res2: = Calc (+, minus) fmt. Println (res1) fmt. PRINTLN (RES2)//anonymous function and ClosureThe so-called closure is a function that "captures" and other constants and variables in the same scope as it does. This means that when a closure is called, the closure is able to use these constants or variables, regardless of where the program is called. It doesn't care if these captured variables and constants have gone out of scope, so only the closures are still in use, and these variables will still exist. In the Go language, all anonymous functions (called function literals in the Go Language specification) are closures. str: = "Ck_god" f1: = Func () {//mode 1:fmt. Printf ("hahaha, I am%s\n", str)} F1 () func () {//Mode 2: Anonymous function FMT. Println ("Sorry, Still Me")} () type Functype func () var f2 functype = f1 F2 ()//Mode 3: Function variable received after call V: = Func (A, b int) (result int) { result = a + b return} (1, 1)//Mode 4: An anonymous function with a parameter that has a return value FMT. Println ("v=", V)//Closures Capture external variable features: Modify the value of the external variable FMT. Println ("\n=========\n") I: = str2: = "Ck_god" func () {i = [+] = "Go" FMT. Printf ("internal: i =%d, str2 =%s\n", I, STR2)} () Fmt. Printf ("external: i =%d, str2 =%s\n", I, str2)//anonymous function as return value f: = Squares () fmt. Println (f ()) fmt. Println (f ()) fmt. Println (f ())///We see that the life cycle of a variable is not determined by its scope: After squares returns, the variable x still implicitly exists in F}
Use of functions, anonymous functions, and recursion in go