Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the '.' (dot or period) in a Go import statement do?

Tags:

import

go

People also ask

What does the dot mean in from of an import?

One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.

How does import work in go?

Importing simply means bringing the specified package from its source location to the destination code, wiz the main program. Import in Go is very important because it helps bring the packages which are super essential to run programs. This article covers various aspects of “Imports in Go”.

Which keyword is used to import packages in a Go program?

The keyword “import” is used for importing a package into other packages. In the Code Listing -1, we have imported the package “fmt” into the sample program for using the function Println. The package “fmt” comes from the Go standard library.


It allows the identifiers in the imported package to be referred to in the local file block without a qualifier.

If an explicit period (.) appears instead of a name, all the package's exported identifiers will be declared in the current file's file block and can be accessed without a qualifier.

Assume we have compiled a package containing the package clause package math, which exports function Sin, and installed the compiled package in the file identified by "lib/math". This table illustrates how Sin may be accessed in files that import the package after the various types of import declaration.

Import declaration          Local name of Sin

import   "lib/math"         math.Sin
import M "lib/math"         M.Sin
import . "lib/math"         Sin

Ref: http://golang.org/doc/go_spec.html#Import_declarations


Here's an analogy for those coming from Python:

  • Go's import "os" is roughly equivalent to Python's import os
  • Go's import . "os" is roughly equivalent to Python's from os import *

In both languages, using the latter is generally frowned upon but there can be good reasons for doing it.


This should only be used in testing.

Here is some documentation in golang's wiki

If you've generated some mock code such as with mockgen and it imports your package code, and then your testing package also imports your package code, you get a circular dependency (Something golang chooses to let the user to decide how to resolve).

However, if inside your testing package you use dot notation on the package you're testing then they are treated as the same package and there is no circular dependency to be had!