Home > Backend Development > Golang > Why Can't I Use Short Variable Declarations (`:=`) at the Package Level in Go?

Why Can't I Use Short Variable Declarations (`:=`) at the Package Level in Go?

DDD
Release: 2024-12-25 09:44:09
Original
734 people have browsed it

Why Can't I Use Short Variable Declarations (`:=`) at the Package Level in Go?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template