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.
Let’s create a new directory named advanced inside math directory. This 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
That’s all about the Nested Packages in Go language. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Go language.!!
Nested Packages in Go