dqpd4268 2018-03-18 08:23
浏览 62
已采纳

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

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条回答 默认 最新

  • doulianqi3870 2018-03-18 08:31
    关注

    The designers of Go chose not to allow this shorthand outside of functions. The Go folks hint at their reasons here

    Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

    Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

    The designers preferred every single statement at the top level to start with a keyword. Perhaps for aesthetics. Perhaps for ease of parsing. Perhaps because the top level things are the things you can export if you capitalize.

    This construct is called both a short assignment statement (in the Go Tour) but officially, in the grammar it is indeed called a short variable declaration! Given that it officially is a declaration, the error message, as you are alluding to, is IMHO wrong! They could do better. They should say "short declaration found outside function."

    UPDATE

    This question looks like a dupe: Why isn't short variable declaration allowed at package level in Go?

    However, if the question is not "why is it not allowed?" but rather "why does the error message say it is a non-declaration?" then it's a good, distinct question.

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

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?