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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With