在 Go 中创建单向通道有什么意义

Iva*_*hko 5 channel go

在 Go 中,可以创建单向通道。如果您想限制给定频道上可用的一组操作,这是一个非常方便的功能。然而,据我所知,这个特性只对函数的参数和变量的类型规范有用,而通过创建单向通道make对我来说看起来很奇怪。我读过这个问题,但这不是关于在 Go 中创建只读(或写)通道,而是关于一般用法。所以,我的问题是关于下一个代码的用例:

writeOnly := make(chan<- string)
readOnly := make(<-chan string)
Run Code Online (Sandbox Code Playgroud)

Ale*_*nok 4

理论上,您可以使用只写通道进行单元测试,以确保您的代码向通道写入的次数不会超过特定次数。

像这样的东西: http: //play.golang.org/p/_TPtvBa1OQ

package main

import (
    "fmt"
)

func MyCode(someChannel chan<- string) {
    someChannel <- "test1"
    fmt.Println("1")
    someChannel <- "test2"
    fmt.Println("2")
    someChannel <- "test3"
    fmt.Println("3")
}

func main() {
    writeOnly := make(chan<- string, 2) // Make sure the code is writing to channel jsut 2 times
    MyCode(writeOnly)
}
Run Code Online (Sandbox Code Playgroud)

但这对于单元测试来说是相当愚蠢的技术。您最好创建一个缓冲通道并检查其内容。