Mark Amery
Mark Amery

Reputation: 154934

Why is the factored import statement better?

The official tour of Go, after exhibiting a factored import like this...

import (
    "fmt"
    "math"
)

... contains the following slightly unclear remark:

You can also write multiple import statements, like:

import "fmt"
import "math"

But it is good style to use the factored import statement.

Is there actually any concrete advantage to using one approach over the other - such as a difference in behaviour or an easy-to-make typo that is only a danger with one of the two syntaxes - or is this just an arbitrary style convention?

Upvotes: 24

Views: 2597

Answers (2)

IamNaN
IamNaN

Reputation: 6864

There is no difference except for the amount of typing you have to do. A good sized program or package can easily have a dozen or more imported packages so why keep typing the same word (import) time and again when you can achieve the same with a pair of ().

Though most people probably use GoImports nowadays anyway.

Upvotes: 20

Salvador Dali
Salvador Dali

Reputation: 222751

There is absolutely no difference for a go compiler. The difference is only for a go programmer in how many times he has to copy/type import. You can look at it in the same way as:

func f1(n1, n2, n3 int){
    ...
}

vs

func f1(n1 int, n2 int, n3 int){
    ...
}

or var n1, n2, n3 int vs

var n1 int
var n2 int
var n3 int

both will produce the same result.

Upvotes: 7

Related Questions