为什么要添加“()”后关闭体在戈兰? [英] Why add "()" after closure body in Golang?

查看:104
本文介绍了为什么要添加“()”后关闭体在戈兰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Go编程语言规范,发现自己在闭包主体后面没有真正理解():

I'm reading The Go Programming Language Specifications and found myself not truly understand with "()" after closure body:

函数文字


func(ch chan int) {ch< - ACK} (replyChan)`

的示例:

// f returns 1
func f() (result int) {
    defer func() {
        result++
    }() // why and how?
    return 0
}

我不清楚要添加的原因&在封闭体之后使用(),希望有人可以清楚地解释这一点。

I'm not clear about the reason to add & usage of "()" after closure body, hope someone can explain this clearly.

推荐答案

必须在 defer 中的闭包之后添加( 延迟声明的语言规范要求其表达式始终为 必须是函数调用。

It's not that () must be added after (only) a closure in defer. The language specs for the defer statement mandate that its 'Expression' always must be a function call.

为什么会这样呢?它与任何其他函数一样,在'defer'或不是:

And why is it so? It's the same as with any other function, in 'defer' or not:

考虑:

func f() int { return 42 }



and

a := f

vs

b := f()

第一个表达式RHS是一个函数值。在第二个版本中,RHS是由函数返回的值 - 即一个函数调用。

The first expression RHS is a function value. In the second version the RHS is the value returned by the function - i.e. a function call.

so的语义如下:

defer f

vs

defer f()

,除了第一个版本在'defer'的上下文中没有意义,因此规范提到它必须是第二个形式(仅)。

except that the first version doesn't make sense in the context of 'defer', and so the specifications mention that it must be the second form (only).

由于与'defer'语句之外的上述函数调用具有正交性,因此IMHO也更容易学习。

It's IMHO also easier to learn because of the orthogonality with the above discussed function call outside of the 'defer' statement.

函数调用不仅仅是fn-expr,后跟(),但表达式列表通常在括号内(包括空列表)。有很大的区别:

Also note that a function call is not only fn-expr followed by (), but an expression list is generally inside the parenthesis (including an empty list). There's a big difference between:

for i := range whatever {
        defer func() { fmt. Println(i) }()
}

for i := range whatever {
        defer func(n int) { fmt. Println(n) }(i)
}

第一个版本打印'在执行闭包的时刻,第二个打印执行延迟语句时的值'i'。

The first version prints the value of 'i' in the moment when the closure executes, the second prints the value of 'i' in the moment when the defer statement was executed.

这篇关于为什么要添加“()”后关闭体在戈兰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆