Function first-class citizen
- You can have multiple return values
- All parameters are passed by value: slice, map, and channel give the illusion of passing references
- A function can be the value of a variable
- Functions can be arguments and return values
The return value more
func returnMultiValues(a) (int.int) {
return rand.Intn(10), rand.Intn(20)}func TestFn(t *testing.T) {
a, _ := returnMultiValues()
t.Log(a)
}
Copy the code
The output
=== RUN TestFn -- PASS: TestFn (0.00s) func_test.go: 14:1 PASS Process finished with exit code 0Copy the code
A small experiment, a function to add time statistics
package func_test
import (
"fmt"
"math/rand"
"testing"
"time"
)
func returnMultiValues(a) (int.int) {
return rand.Intn(10), rand.Intn(20)}func timeSpent(inner func(op int)int) func(op 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))}Copy the code
The output
=== RUN TestFn time spent: 1.00139513 <----- -- PASS: TestFn (1.00s) func_test.go:31: 1 func_test.go:33: 10 PASS Process finished with exit code 0Copy the code
The above example is like the decorator pattern in design mode, where we just add a layer on top of the original function without changing the original function
Sample code can be found at: github.com/wenjianzhan…