Go Keyword import: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 22: Line 22:
<pre>
<pre>
...
...
import "lib/math"
import "net/http"
...
...
</pre>
</pre>

Revision as of 00:02, 2 April 2016

External

Internal

Overview

An import declaration states that the current package depends on the functionality of the imported package and wants access to its name space. Thus, the current package gains access to the exported identifiers exposed by the imported package.

...
import [package-name-alias] "package-path-string-literal"
...

Example

...
import "net/http"
...

The package path is enclosed in double quotes, it is a string literal. It represents a path on the local file system that lives under a src directory whose parent is listed in GOPATH. For more details on how GOPATH works go to GOPATH.

The package-name-alias is optional. If not specified, the package will be referred as the last segment of the path.

Importing Multiple Packages

import (
    "fmt"
    "strings"
)

Accessing an Identifier from an Imported Package

Once a package has been declared as "imported", all exported identifiers from the imported package are available in the importing package. In order to access an individual exported identifier, the identifier should be prefixed with the name of the package. For example, in order to access the struct Box exposed by package "pkgA", we do this:

import "pkgA"
...
func f() {
    ...
    var b pkgA.Box
    ...
}

How Packages are Resolved

The algorithm is described here:

GOPATH