返回两个通道的GoRoutine

时间:2019-01-07 18:03:55

标签: function go

有人可以帮我理解如何在函数返回中解释以下代码-(_,_ <-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 个答案:

答案 0 :(得分:2)

(_, _ <-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{})

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

答案 1 :(得分:0)

这是class A { constructor() { this.element = document.querySelector('.element') } } class B { constructor() { this.a = new A() } someMethod() { // Here I need to set a style of this.a.element // should I manipulate the style directly: this.a.element.style.marginBottom = '10px' // or should I use a method: this.a.setElementStyle('marginBottom', '10px') } } 声明

func

如您所见,FunctionType = "func" Signature . Signature = Parameters [ Result ] . Result = Parameters | Type . Parameters = "(" [ ParameterList [ "," ] ] ")" . ParameterList = ParameterDecl { "," ParameterDecl } . ParameterDecl = [ IdentifierList ] [ "..." ] Type . 就像方法的参数Result一样,它又归结为Parameters。空白标识符IdentifierList可以替换_中的每个标识符。

原始作者将其与“声明为相同类型的多个标识符”语法一起使用,以产生-如前所述-读取两个相同类型的返回值的声明很奇怪。

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

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

IdentifierList

第二个参数不可用。