dqpd4268
dqpd4268
2018-03-18 08:23

如果在主体函数体之外编写,GoLang中的“ var deckSize = 20”和“ deckSize:= 20”之间有什么区别? [重复]

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

I am new to Go, and learning the basics of the language. This is where I am stuck.

I understand from the basic course that var x int = 10 and x := 10 are supposed to be equivalent, the latter being a shorthand notation. It all made sense till these two were inside the main() function.

That means:

package main
import "fmt"   

func main() {
    var x int = 20
    fmt.Println(x)
}

,

func main() {
    var x := 20
    fmt.Println(x)
}

and

func main() {
    x := 20
    fmt.Println(x)
}

All these run fine. But when I move this variable outside the main function, the behavior is different and I couldn't find an explanation in the tutorials I could find.

That means,

package main

import "fmt"

var x int = 20

func main() {
    fmt.Println(x)
}

and

var x = 20

func main() {
    fmt.Println(x)
}

run as expected, but,

x := 20

func main() {
    fmt.Println(x)
}

Gives an error :

syntax error: non-declaration statement outside function body

Why did this statement become a "non-declaration" one, and how is it different from same syntax being used inside the main() function?

</div>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐