duankanyi6539 2014-11-15 22:38
浏览 5
已采纳

新增功能,括号中的解释[重复]

This question already has an answer here:

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")
}
</div>
  • 写回答

1条回答 默认 最新

  • dsgd5756 2014-11-15 22:42
    关注

    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?".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)