为了账号安全,请及时绑定邮箱和手机立即绑定

返回两个通道的 GoRoutine

返回两个通道的 GoRoutine

Go
鸿蒙传说 2023-06-01 10:02:59
有人可以帮我理解如何解释函数返回中的以下代码行 - (_, _ <-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}`
查看完整描述

2 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

(_, _ <-chan interface{})相当于(<-chan interface{}, <-chan interface{}). 除了源代码长度和可读性之外,没有区别。

  1. (<-chan interface{}, <-chan interface{})我们从返回值类型开始。

  2. 由于返回值可以有名称,因此可以写入(ch1 <-chan interface{}, ch2 <-chan interface{})返回相同的 2 个通道。

  3. 具有相同类型的参数序列(或返回值)可以省略除最后一个变量之外的所有变量的类型。因此我们的返回类型变成:(ch1, ch2 <-chan interface{})

  4. 因为我们真的不需要返回值的名称,我们可以用下划线替换名称,再次使它们匿名:(_, _ <-chan interface{})

瞧!同一类型的可读通道对。


查看完整回答
反对 回复 2023-06-01
?
慕的地6264312

TA贡献1817条经验 获得超6个赞

这是func声明


FunctionType   = "func" Signature .

Signature      = Parameters [ Result ] .

Result         = Parameters | Type .

Parameters     = "(" [ ParameterList [ "," ] ] ")" .

ParameterList  = ParameterDecl { "," ParameterDecl } .

ParameterDecl  = [ IdentifierList ] [ "..." ] Type .

如您所见, theResult就像方法的参数 a Parameters,后者又归结为IdentifierList. 出现了空白标识符_,可以替换IdentifierList.


原作者将此与“声明为同一类型的多个标识符”语法一起使用,以产生 - 正如已经提到的 - 一种奇怪的阅读声明,其中包含两个相同类型的返回值。


请参阅https://golang.org/ref/spec#Function_declarations


您还可以通过使用空白标识符来实现“删除”参数的功能。当您不需要您实现的接口的参数时,可能会派上用场。


func foo(a string, _ int, b string) { ... }

第二个参数不可用。


查看完整回答
反对 回复 2023-06-01
  • 2 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信