Nested Packages in Go


Nested Packages in Go

In this tutorial, we will discuss nested packages in GO language. In GO language, it is possible to create nested packages.

Nested Packages in Go

Let’s create a new directory named advanced inside math directoryThis directory will contain square.go file which will package declaration as “package advanced”.

go mod init waytoeasylearn.com/learn

go.mod

module waytoeasylearn.com/learn

go 1.14

learn/math/math.go

package math

func Add(a, b int) int {
    return a + b
}

func Subtract(a, b int) int {
    return a - b
}

learn/math/advanced/advanced.go

package advanced

func Square(a int) int {
    return a * a
}

learn/main.go

package main

import (
    "fmt"
    "waytoeasylearn.com/learn/math"
    "waytoeasylearn.com/learn/math/advanced"
)

func main() {
    fmt.Println(math.Add(5, 10))
    fmt.Println(math.Subtract(20, 10))
    fmt.Println(advanced.Square(2))
}

Let’s run this program

learn $ go install
learn $ learn
15
10
4

Points to note about above program

  • We imported the advanced package in main.go with full qualified path i.e.  import “waytoeasylearn.com/learn/math/advanced”
  • The Square function is referred to using advanced package i.e. advanced.Square(2)
  • As mentioned earlier, directory name can be other advanced, just that it has to be imported accordingly
  • Also, filename can be anything other than advanced.go
Nested Packages in Go

Scroll to top