Short Variable Declaration at Package Level
In Go, short variable declaration (using :=) is allowed within functions, but not at the package level. This can be puzzling, as using := outside a function looks like regular declaration without a type.
Reason for the Restriction
According to Ian Lance Taylor, one of Go's creators, the restriction exists solely to simplify parsing. Top-level declarations always start with a keyword, such as var, func, import, etc. This simplifies the syntax and makes parsing more straightforward for the compiler.
Example
Package-level declaration using var is allowed:
Short variable declaration using := is not allowed at package level:
The above is the detailed content of Why Can't I Use Short Variable Declarations (`:=`) at the Package Level in Go?. For more information, please follow other related articles on the PHP Chinese website!