go defer 使用

  • 2022-07-09
  • 浏览 (1002)

golang defer 使用样例

package main

import (
	"fmt"
	"gotest/common"
	"testing"
	"time"
)

// test 测试函数
func TestDefer(t *testing.T) {
	common.Println("hi, main thread")
	defer fmt.Println(`exiting now`)
	go fmt.Println("hi, sub one thead")
	go fmt.Println("hi sub two thread")
	fmt.Println("end")
	return
}

// -bench 基准测试
func BenchmarkSum(b *testing.B) {
	sum := 0
	for i := 0; i < b.N; i++ {
		sum += i
	}
}

// -timeout 测试
func TestSumLongTime(t *testing.T) {
	time.Sleep(time.Second * 2)
	fmt.Println("testTime")
}

// -example 测试
func ExamplePrintln() {
	Println()
	//Output: this is an example.
}

func Println() {
	fmt.Println("this is an example.")
}

测试

执行测试代码 go test -v defer_test.go 可以查看执行结果

go test 使用请看:go test 使用

golang 使用样例汇总:go test

你可能感兴趣的文章

go array 使用

go file 使用

go func 使用

go http 使用

go interface 使用

go main 使用

go map 使用

go math 使用

go method 使用

go range 使用

0  赞