Go 实践记录1 | 青训营

64 阅读1分钟

单元测试:

  • 测试函数命名为 func TestXxx(t *testing.T)

  • 测试文件命名:“_test.go” , 位于被测文件的同一个 package 下,或者位于 package xxx_test 下

  • 例子

    // abs.go
    package main
    ​
    func Abs(n int) int {
        if n >= 0 {
            return n
        }
        return -n
    }
    
    // abs_test.go
    package main
    ​
    import "testing"func TestAbs(t *testing.T) {
        got := Abs(-1)
        if got != 1 {
            t.Errorf("Abs(-1) = %d; want 1", got)
        }
    }
    

Benchmarks 测试

  • 测试函数命名为 func BenchmarkXxx(*testing.B)

  • executed by the "go test" command when its -bench flag is provided

go1.jpg

  • 结果说明

    • BenchmarkRandInt-20 :测试函数名,20 表示 GOMAXPROCS=20,默认CPU核数
    • 100000000 :一共执行 100000000 次,即 N=100000000
    • 每次执行耗时 11.41 ns/op
    • 每次执行申请内存 0 B/op
    • 每次执行申请 0 allocs/op 次内存

管道 chan 的使用方法:

func boring(msg string, c chan string) {
    for i := 0; ; i++ {
        // 发送信息给管道 (hannel / chan)
        // 同时,它也在等待管道的消费者消费完成
        c <- fmt.Sprintf("%s %d", msg, i)
        time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
    }
}
​
func main() {
    c := make(chan string) // 初始化一个管道
    go boring("boring!", c)
​
    for i := 0; i < 5; i++ {
        // `<-c` 等待 `boring` 方法给它发送值,如果一直没有收到,那么会被阻塞在这一步
        fmt.Printf("You say: %q\n", <-c)
    }
    fmt.Println("You're boring. I'm leaving")
}

在Go语言中,通道是goroutine与另一个goroutine通信的媒介,并且这种通信是无锁的。

通道是一种允许一个goroutine将数据发送到另一个goroutine的技术。 默认情况下,通道是双向的,这意味着goroutine可以通过同一通道发送或接收数据

创建单向管道,如<-chan string只能从管道中读取数据,而chan<- string只能够向管道中写入数据