新手入门,括号解释

huangapple go评论75阅读模式
英文:

New to go, paren explanation

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,遇到了一组我不理解的括号。

在下面的代码中,我使用了一个基本的defer语句来打印panic的输出。

为了让代码正常工作,我必须在函数结束的右花括号后面添加一个开括号和闭括号。

显然,我对某些事情的理解不正确。如果上面的两行是函数体,那么括号在其后的作用是什么?如果它们不是函数体,那么有人能解释一下这里发生了什么吗?

如果没有括号,我会得到以下错误:

# command-line-arguments ./goTemplate.go:14: syntax error: argument to go/defer must be function call

package main
import "fmt"

func main(){
    defer func() {
        str := recover()
        fmt.Println(str)
    }()
    fmt.Println("Hello, World")
    panic("PANIC")
}

希望对你有帮助!

英文:

I am new to go and have come across a set of parens I don't understand.

In the code below I am using a basic defer statement to print the output of a panic.

To get the code to work I have to add an open and close paren after the end of my functions closing curly brace.

Clearly I don't understand something properly. Am I incorrect in thinking that the two lines above it are the body of the function? If they are the body of the function then what purpose do the parens after it serve. If they are not the body then can someone explain what is happening here?

the error I get without the parens is:

# command-line-arguments
./goTemplate.go:14: syntax error: argument to go/defer must be function call
.

package main
import "fmt"

func main(){
    defer func() {
	    str := recover()
	    fmt.Println(str)
    }()
    fmt.Println("Hello, World")
    panic("PANIC")
}

答案1

得分: 1

延迟规范中可以看到:

> 表达式必须是一个函数或方法调用;

在你的情况下,它是一个函数调用:()调用了该函数。
如果没有(),它将是一个函数

你可以在"为什么在Golang中在闭包体后面添加“()"中了解更多信息。

英文:

From the Defer spec:

> The expression must be a function or method call;

In your case, it is a function call: the () invokes the function).
Without the (), it would be a function value.

You can see more at "Why add “()” after closure body in Golang?".

huangapple
  • 本文由 发表于 2014年11月16日 06:38:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/26951568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定