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 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题