As pointed out by others, both forms can be used in all cases.
This grouping is allowed in almost all top-level identifiers (import
, var
, const
and type
), and its purpose is to give you the possibility to better organize and logically group your identifiers. (Note that you may also group inside a function not just at the top-level.)
With the case of import
, tools like gofmt
will order imports within a group primiarily by origin (standard lib or not), and secondary by import path alphabetically, but they don't reorganize between groups or the groups themselves.
In case of const
it has another significance: the keyword const
resets the iota
predeclared identifier, so properly grouping constants when using iota
is vital.
Other than that, it doesn't matter, you may use both forms. Group your identifiers based on their meaning and how they connect to each other. For example grouping a sync.Mutex
with the variable it ought to protect is also handy:
var (
mu sync.Mutex
protectMe int
)
func getMe() int {
mu.Lock()
me := protectMe
mu.Unlock()
return me
}
func setMe(me int) {
mu.Lock()
protectMe = me
mu.Unlock()
}
(Example taken from How to make a variable thread-safe.)
As I remember from the various Go talks I've watched, the Go programming language prides itself for being a simple, easy-to-use language that doesn't have 10 different ways to do one thing.
Don't interpret this the wrong way. Both way of importing is the same, just formatted differently. Both specify the same set of imported packages. Just because a language allows you to add a
and b
in 2 ways, e.g. a+b
and b+a
, that doesn't mean a simple addition is allowed to be expressed in multiple ways.