github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch2/13_func_test.go (about)

     1  package ch2
     2  
     3  import (
     4  	"fmt"
     5  	"math/rand"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func returnMultiValues() (int, int) {
    11  	return rand.Intn(10), rand.Intn(20)
    12  }
    13  
    14  // ------------- 统计操作时长 ------------------------------ //
    15  func timeSpent(inner func(op int) int) func(op int) int {
    16  	return func(n int) int {
    17  		start := time.Now()
    18  		ret := inner(n)
    19  
    20  		fmt.Println("time spent: ", time.Since(start).Seconds())
    21  		return ret
    22  	}
    23  }
    24  
    25  func slowFun(op int) int {
    26  	time.Sleep(time.Second * 3)
    27  	return op
    28  }
    29  
    30  func TestFn(t *testing.T) {
    31  	//a, b := returnMultiValues()
    32  	//t.Log(a, b)
    33  
    34  	time := timeSpent(slowFun)
    35  	t.Log("调用 timeSpent 方法", time(10))
    36  }
    37  
    38  // ------------- 可变长度参数 ------------------------------ //
    39  
    40  func Sum(ops ...int) int {
    41  	ret := 0
    42  	for _, op := range ops {
    43  		ret += op
    44  	}
    45  	return ret
    46  }
    47  
    48  func TestVarParm(t *testing.T) {
    49  	t.Log(Sum(1, 2, 3, 4, 5))
    50  	t.Log(Sum(1, 2, 3, 4))
    51  
    52  }
    53  
    54  // ------------- defer(延迟)函数(类似于 finally 的作用) ------------------------------ //
    55  func Clear() {
    56  	fmt.Println("3. clear resources 2")
    57  }
    58  
    59  func TestDefer(t *testing.T) {
    60  	defer Clear()
    61  
    62  	defer func() {
    63  		t.Log("2. clear resources 1")
    64  	}()
    65  
    66  	fmt.Println("1. 开始")
    67  	//panic("err")
    68  }