Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the factored import statement better?

Tags:

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?

like image 780
Mark Amery Avatar asked May 24 '15 15:05

Mark Amery


People also ask

What is factored import statement?

The "factored" import statement groups the imports into a parenthesized. Syntax: import ( package_1 package_2 ... ) Example: import ( "fmt" "time" ) In the below program, we are using two packages fmt and strings and these packages are importing through the factored import statement.

Which is the only valid import statement in go?

The answer is simple: using the “import” keyword. As the name suggests, this keyword imports the specified package from the directory of $GOPATH (if no path is mentioned) or else from the mentioned directory.

What are named imports in Golang?

Golang Named Imports The above example uses fmt package that comes as a part of the standard library and the second imported package name is also fmt that is created by the user. If we try to access the exported functions from both fmt packages we can't do it as both have the same name.


1 Answers

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.

like image 133
IamNaN Avatar answered Oct 09 '22 21:10

IamNaN