Packages in Go

codehakase

Francis Sunday

Posted on December 4, 2017

Packages in Go

Hey there! if you've been following the series, you're awesome!!!.

In the last article, we looked at functions in Go, and how to define them. In this part, we're gonna look at Packages.

What are Packages?

Packages are used to organize source code for better reuseablity and readability. Packages makes it easy to maintain Go applications.

So far in the previous articles, we've been seeing programs which have only one file with a main function with along side other functions. Writing all source code in a single file somethings isn't a good approach, since it becomes pretty hard to maintain and reuse code.

## Main package and main function
Every executable Go program, must contain a main function. The main function serves as an entry point for execution.

The main function should reside in the main package.

Packages are defined in a source file as package packageName, which is at the first line of the source file.

Imports

The import "packagename" statement is used to import existing packages into a Go source. When a package is imported, you have access to the methods defined in that package:

package main

import "fmt"

func main() {
  fmt.Println("Hello Golang Packages!!!")
}
Enter fullscreen mode Exit fullscreen mode

Custom Packages

Let's create a custom package geometry a package with minimal geometry calculations.

Note: Source files belonging to a package should be placed in separate folders of their own. It is a convention in Go to name this folder with the same name of the package.

Let's create the directory structure for our package,

$ cd $HOME/gocode/src
$ mkdir geometry
Enter fullscreen mode Exit fullscreen mode

We'll create a new file rectangle/rectangle.go with the following:

package rectangle

import "math"

func Diagonal(len, wid float64) float64 {  
    diagonal := math.Sqrt((len * len) + (wid * wid))
    return diagonal
}

func Area(len, wid float64) float64 {  
    area := len * wid
    return area
}
Enter fullscreen mode Exit fullscreen mode

In the above code we have created two functions which calculates the Area and Diagonal of a rectangle. The area of the rectangle is the product of the length and width. The diagonal of the rectangle is the square root of the sum of squares of the length and width. The Sqrt function in the math package is used to calculate the square root.

Importing Custom Packages

To use a custom package we must first import it. We must specify the path to the custom package with respect to the src folder inside the workspace.

Let's create our entry file, geometry.go which will contain the main function for our Package.


package main

import (
  "fmt"
  "geometry/rectangle"
)

func main() {
    var rectLen, rectWidth float64 = 6, 7
    fmt.Println("Geometrical shape properties")
        /*Area function of rectangle package used
        */
    fmt.Printf("area of rectangle %.2f\n", rectangle.Area(rectLen, rectWidth))
        /*Diagonal function of rectangle package used
        */
    fmt.Printf("diagonal of the rectangle %.2f ",rectangle.Diagonal(rectLen, rectWidth))
}
Enter fullscreen mode Exit fullscreen mode

The above code imports the rectangle package and uses the Area and Diagonal function of it to find the area and diagonal of the rectangle. The %.2f format specifier in Printf is to truncate the floating point to two decimal places. The output of the application is:

Geometrical shape properties  
area of rectangle 42.00  
diagonal of the rectangle 9.22  
Enter fullscreen mode Exit fullscreen mode

Exported Names

We capitalized the functions Area and Diagonal in the rectangle package. This has a special meaning in Go. Any variable or function which starts with a capital letter are exported names. Only exported functions and variables can be accessed from other packages. In this case we need to access Area and Diagonal functions from the main package. Hence they are capitalized.

init function

Every package can contain an init function. The init function should not have any return type and should not have any parameters. The init function cannot be called explicitly in our source code. The init function looks like below

func init() {  
}
Enter fullscreen mode Exit fullscreen mode

The init function can be used to perform initialization tasks and can also be used to verify the correctness of the program before the execution starts.

The order of initialization of a package is as follows

  • Package level variables are initialized first
  • init function is called next. A package can have multiple init functions (either in a single file or distributed across multiple files) and they are called in the order in which they are presented to the compiler.

If a package imports other packages, the imported packages are initialized first.

That's it for packages. Packages helps us organize code in a very clean way, create utilities for our programs that can be distributed.

If I've missed anything, let me know in the comments.

💖 💪 🙅 🚩
codehakase
Francis Sunday

Posted on December 4, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related