Developing your own Go packages

The source code of a Go package, which can contain multiple files and multiple directories, can be found within a single directory that is named after the package name with the obvious exception of the main package that can be located anywhere.

For the purposes of this section, a simple Go package named aPackage will be developed. The source file of the package is called aPackage.go, and its source code will be presented in two parts.

The first part of aPackage.go is shown in the following Go code:

package aPackage 

import ( 
   "fmt" 
) 
 
func A() { 
   fmt.Println("This is function A!") 
} 

The second code segment of aPackage.go follows next:

func B() { 
   fmt.Println("privateConstant:", privateConstant) 
} 
 
const MyConstant = 123 
const privateConstant = 21 

As you can see, developing a new Go package is pretty easy! Right now you cannot use that package on its own, and you need to create a package named main with a main() function in it in order to create an executable file. In this case, the name of program that will use aPackage is useAPackage.go, and it's included in the following Go code:

package main 
 
import ( 
   "aPackage" 
   "fmt" 
) 
 
func main() { 
   fmt.Println("Using aPackage!") 
   aPackage.A() 
   aPackage.B() 
   fmt.Println(aPackage.MyConstant) 
} 

If you try to execute useAPackage.go right now, however, you will get an error message, which means that you are not done yet:

$ go run useAPackage.go
useAPackage.go:4:2: cannot find package "aPackage" in any of:
      /usr/local/Cellar/go/1.9.2/libexec/src/aPackage (from $GOROOT)
      /Users/mtsouk/go/src/aPackage (from $GOPATH)

There is another thing that you will also need to handle. As you already know from Chapter 1, Go and the Operating System, Go requires to execute specific commands from the Unix shell in order to install all external packages, which also includes packages that you have developed. Therefore, you will need to put the preceding package in the appropriate directory and make it available to the current Unix user. Thus, installing one of your own packages involves the execution of the following commands from your favorite Unix shell:

$ mkdir ~/go/src/aPackage
$ cp aPackage.go ~/go/src/aPackage/
$ go install aPackage
$ cd ~/go/pkg/darwin_amd64/
$ ls -l aPackage.a
-rw-r--r--  1 mtsouk  staff  4980 Dec 22 06:12 aPackage.a
If the ~/go directory does not already exist, you will need to create it with the help of the mkdir(1) command. In that case, you will also need to do the same for the ~/go/src directory.

Executing useAPackage.go will create the following output:

$ go run useAPackage.go 
Using aPackage! 
This is function A! 
privateConstant: 21 
123 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.194.57