返回两个通道的 GoRoutine

有人可以帮我理解如何解释函数返回中的以下代码行 - (_, _ <-chan interface{})


我知道该函数返回两个通道。但是我不明白它是如何使用以下(_,_ <-chan interface{})实现的。如果我只是将它换成 (<-chan interface{}, <-chan interface{}) 有什么区别?


tee := func(

    done <-chan interface{},

    in <-chan interface{},

) (_, _ <-chan interface{}) {

    out1 := make(chan interface{})

    out2 := make(chan interface{})


    go func() {

        defer close(out1)

        defer close(out2)


        for val := range orDone(done, in) {

            var out1, out2 = out1, out2

            for i := 0; i < 2; i++ {

                select {

                case <-done:

                case out1 <- val:

                    out1 = nil

                case out2 <- val:

                    out2 = nil

                }

            }

        }

    }()

    return out1, out2

}`


鸿蒙传说
浏览 69回答 2
2回答

慕尼黑的夜晚无繁华

(_, _ <-chan interface{})相当于(<-chan interface{}, <-chan interface{}).&nbsp;除了源代码长度和可读性之外,没有区别。(<-chan interface{}, <-chan interface{})我们从返回值类型开始。由于返回值可以有名称,因此可以写入(ch1 <-chan interface{}, ch2 <-chan interface{})返回相同的 2 个通道。具有相同类型的参数序列(或返回值)可以省略除最后一个变量之外的所有变量的类型。因此我们的返回类型变成:(ch1, ch2 <-chan interface{})因为我们真的不需要返回值的名称,我们可以用下划线替换名称,再次使它们匿名:(_, _ <-chan interface{})瞧!同一类型的可读通道对。

慕的地6264312

这是func声明FunctionType&nbsp; &nbsp;= "func" Signature .Signature&nbsp; &nbsp; &nbsp; = Parameters [ Result ] .Result&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;= Parameters | Type .Parameters&nbsp; &nbsp; &nbsp;= "(" [ ParameterList [ "," ] ] ")" .ParameterList&nbsp; = ParameterDecl { "," ParameterDecl } .ParameterDecl&nbsp; = [ IdentifierList ] [ "..." ] Type .如您所见, theResult就像方法的参数 a Parameters,后者又归结为IdentifierList. 出现了空白标识符_,可以替换IdentifierList.原作者将此与“声明为同一类型的多个标识符”语法一起使用,以产生 - 正如已经提到的 - 一种奇怪的阅读声明,其中包含两个相同类型的返回值。请参阅https://golang.org/ref/spec#Function_declarations您还可以通过使用空白标识符来实现“删除”参数的功能。当您不需要您实现的接口的参数时,可能会派上用场。func foo(a string, _ int, b string) { ... }第二个参数不可用。
打开App,查看更多内容
随时随地看视频慕课网APP