Functions are first-class citizens
The main difference with other programming languages
1. There may be multiple return values
2. All parameters are passed by value
slice, map, channel will be passed by reference is an illusion, as is behind the array slice is a data structure which contains pointers pointing to the corresponding array, the data structure is copied, the same pointer operation is still a space feel like mass quote
3 as a function of the value of a variable
4 function as parameters and return values
fun_test Package Import ( " FMT " " Math / RAND " " Testing " " Time " ) // multiple return values FUNC returnMultiValues () ( int , int ) { return rand.Intn ( 10 ), rand.Intn ( 20 is ) } // function arguments and return values as // calculate inner function of the operating time of FUNC timeSpent (inner FUNC (OP int ) int ) FUNC (opt int ) int { return FUNC (n- int )int { start := time.Now() ret := inner(n) fmt.Println("time spent:", time.Since(start).Seconds()) return ret } } func slowFun(op int)int{ time.Sleep(time.Second*1) return op } func TestFn(t *testing.T){ a, _ := returnMultiValues() t.Log(a) tsSF := timeSpent(slowFun) t.Log(tsSF(10)) }
result:
=== RUN TestFn
time spent: 1.0000582
--- PASS: TestFn (1.00s)
func_test.go:32: 1
func_test.go:34: 10
PASS
to be continued------------------------------------------------ -