function
Functions are first-class citizens in GO, the same as in JS.
Normal functions need to be declared before they can be called:
var str string="this is a string!" Func addAtoB(a,b int b)(sumAB int){sumAB=a+b return sumAB}Copy the code
1.1 Variable scope
A variable declared in the body of a function is called a local variable. Its scope is only in the body of a function. The declaration period is only in the body of a function. Variables declared outside of a function are called global variables
1.2 Anonymous Functions
1.2.1 Usage of anonymous Functions 1
package main
import "fmt"
func main() {
func(data int){
fmt.Printf("this is a func%d",data)
}(100)
}
Copy the code
1.2.2 Anonymous Function Method 2: Assign a function to a variable
package main
import "fmt"
func main() {
str:= func(name string) {
fmt.Println("hello,"+name)
}
str("JackMa")
}
Copy the code
1.2.3 Anonymous Functions as callback functions
A simple callback function example
FuncType Func (float64,float64)float64 Func sum(a, B float64)(c float64) {c=a+b return c} func difference(a, B float64)(c float64) {c=a-b Return c} // Func product(a,b float64)(c float64) {c=a*b return c} // Here calc is a callback function func calc(f funcType,a,b float64)(ret Float64) {ret=f(a,b) return ret} func main() {ret:=calc(sum,10.0,20) FMT.Println(ret) ret=calc(difference,10,20) FMT. Println (ret) ret = calc (100200) product, FMT. Println (ret)}Copy the code
1. The closure
Closures are an old concept, and they exist in JS as well as rust. A closure essentially returns a function that accesses variables in the function’s scope, resulting in a closure.
package main import "fmt" func main() { pos:=adder() for i:=1; i<10; i++ { fmt.Printf("i=%d\t",i) fmt.Println(pos(i)) } fmt.Println("----------------") for i:=0; i<10; I ++{fmt.printf (" I =%d", I) fmt.println (pos(I))}} func adder() func(int)int {// Here is an adder function, adder returns a function. Sum :=0 return func(x int) int {// Sum is inside the scope of adder. Printf("sum=%d\t",sum) sum+=x fmt.Printf("sum2=%d\t",sum) return sum}} /* i=1 sum=0 sum2=1 1 i=2 sum=1 sum2=3 3 */Copy the code
1.2.5 Variable Parameters
A variable parameter is a variable number of functions, the same type, you can use a variable parameter.
Sample is a summation function of different numbers
package main import "fmt" func getSum(val ... Float64)(sum float64) {sum=0 for _,value:=range val{sum+=value} return sum} func main() { Println(getSum(2,4,6,8,10)) // returns 30}Copy the code
1.2.6 recursive
Recursion is a function calling itself
Sample computes the factorial recursion
package main func prod(val,sum int)(s int) { if(val==1){ return sum } sum*=val val-- return prod(val,sum) } func main() {ret: = prod (1, 1) println (ret)}Copy the code