Almost everything we want to do in Go comes from some package. And to use those packages, we need to import them. In this post, we will explore different import methods available in Go.
Types of imports in Go
Go has different kinds of imports that are used for different cases. Here are the import types Go supports.
1. Import each package directly
Go supports the direct import of each of the packages as well as grouped import. Here is the way to do that.
import "fmt" // import packages one by one
import "os"
Here is the grouped import syntax.
import (
"fmt"
"os"
)
2. Aliased imports in Go
Go supports aliased imports that means we can use aliasing to define another name of the same package, that way we can avoid writing large names of the packages when calling functions from them.
package main
import f "fmt"
func main() {
f.Println("Hello, World") // Hello, World
}
3. The dot import
We can use a dot before importing the entire package into the same namespace. So, we don’t have to call the functions using the package name. We can directly call them. This has some drawbacks associated with it since it mixes up the packaging and can cause namespace collisions.
package main
import (
. "fmt" // import using .
)
func main() {
// call function without package name
Println("It Works") // It Works
}
4. The blank imports
The imports in Go can have the blank identifier before it so that the compiler can ignore the unused import error. When we import some packages in Go and don’t use it anywhere, Go complaints about it. The blank identifier can be used to ignore that.
package main
import _ "os" // ignore the unused import
import "fmt"
func main(){
fmt.Println("It works") // It works
}
5. Nested imports in Go
When all we want is a subpackage of a larger package, we don’t need to import all of it. We can simply get away with the subpackage import. Here is the example showing the nested import of the rand package from the math package.
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Int()) // 134020434
}
These are some of the ways of importing packages is available in Go.