Golang: Package, Import

By Xah Lee. Date: . Last updated: .

Every Go program is made up of packages.

Programs start running in package named “main”, with function “main”.

package main

import "fmt"

func main() {
	fmt.Println(3 + 4) // 7
}

Every go source code file have the above structure.

Import

import name
Import a package named name.
The name should be a string.
import (name1; name2 etc)
Import multiple packages, with one single import statement.
package main

import "fmt"
import "math"

func main() {
	fmt.Printf("%v\n", math.Sqrt(9)) // 3
}
package main

import ( "fmt"; "math" )

func main() {
	fmt.Printf("%v\n", math.Sqrt(9)) // 3
}

Semicolon Optional

Semicolon ; is optional when it is at end of line.

Format Source Code: gofmt

The command line tool gofmt, bundled with golang, will reformat your go source code to a standard format. Run it in terminal like this: gofmt fileName

Exported Names, Begin with Upper Case

A name is exported if it begins with a capital letter.

When importing a package, you can refer only to its exported names. Any “unexported” names are not accessible from outside the package.

Golang

Examples

Reference