var vs := in Go

后端 未结 3 907
滥情空心
滥情空心 2020-12-30 19:53

In the Go web server example here: http://golang.org/doc/effective_go.html#web_server

The following line of code works

var addr = flag.String(\"addr\         


        
3条回答
  •  一个人的身影
    2020-12-30 20:32

    The Go Programming Language Specification

    Short variable declarations

    A short variable declaration uses the syntax:

    ShortVarDecl = IdentifierList ":=" ExpressionList .
    

    Short variable declarations may appear only inside functions.

    In your example, changing the variable declaration statement outside a function body

    var addr = flag.String("addr", ":1718", "http service address")
    

    to a short variable declaration statement outside a function body

    addr := flag.String("addr", ":1718", "http service address")
    

    fails with compiler error "non-declaration statement outside function body."

提交回复
热议问题