Packages

"


Answer to whether there is a bit wise negation operator – Ken Thompson

A package is a collection of functions and data.

You declare a package with the package keyword. Thefilename does not have to match the package name. The convention for packagenames is to use lowercase characters. Go packages may consist of multiple files,but they share the package <name> line. Let’s define a package even in thefile even.go.

  1. package even 1
  2. func Even(i int) bool { 2
  3. return i%2 == 0
  4. }
  5. func odd(i int) bool { 3
  6. return i%2 == 1
  7. }

Here 1 we start a new namespace: “even”. The function Even 2 starts witha capital letter. This means the function is exported, and may be used outsideour package (more on that later). The function odd 3 does not start witha capital letter, so it is a private function.

Now we just need to build the package. We create a directory under $GOPATH,and copy even.go there (see in ).

  1. % mkdir $GOPATH/src/even
  2. % cp even.go $GOPATH/src/even
  3. % go build
  4. % go install

Now we can use the package in our own program myeven.go:

  1. package main
  2. import ( 1
  3. "even" 2
  4. "fmt" 3
  5. )
  6. func main() {
  7. i := 5
  8. fmt.Printf("Is %d even? %v\n", i, even.Even(i)) 4
  9. }

Import 1 the following packages. The local package even is imported here2. This 3 imports the official fmt package. And now we use 4 thefunction from the even package. The syntax for accessing a function froma package is <package>.FunctionName(). And finally we can build our program.

  1. % go build myeven.go
  2. % ./myeven
  3. Is 5 even? false

If we change our myeven.go at 4 to use the unexported function even.odd:fmt.Printf("Is %d even? %v\n", i, even.odd(i)) We get an error when compiling,because we are trying to use aprivate function:

  1. myeven.go: cannot refer to unexported name even.odd

Note that the “starts with capital (\rightarrow) exported”, “starts withlower-case (\rightarrow) private” rule also extends to other names (newtypes, global variables) defined in the package. Note that the term “capital” isnot limited to US-ASCII – it extends to all bicameral alphabets (Latin, Greek,Cyrillic, Armenian and Coptic).