Importing Local Package in Go Lang

In a conventional object oriented language like C#, we have something called a namespace. Classes defined under a namespace can be imported into another class by using the namespace import.

In go, we divide the code into multiple packages. Usually a package is enforced around a feature/functionality that the code provides. That been said, the approach to import a package into another is not same as a conventional oops language.

Please follow below example in which we have created and imported a package.

1. Create a main package and main function and add some print statement to it.

package main

import (
	"fmt"

)

func main() {
	fmt.Println("Hi, this is go")
	
}

2. Now create/initiate a go mod by using the below command

go mod init gotest

# this name gotest can be anything

3. Now create another folder, our example if samplepackage(this name can be anything) and add a file into it. The file name can also be anything. Our exmaple file in entry.go

4. In this newly created file, define a package. Please note that this package name should be the same as the folder name in which this file exists. Also, add a sample function which returns some text.

package samplepackage

func Test() string {
	return "This is a test string"
}

5. Now, we import this into our main.go file using the name "gotest/samplepackage", where gotest is the name of our app folder and "samplepackage" is the package name that we created in entry.go

6. We can now call the Test() method in our main.go, as shown below:

package main

import (
	"fmt"
	"gotest/samplepackage"
)

func main() {
	fmt.Println("Hi, this is go")
	fmt.Println(samplepackage.Test())
}

The output that we see is as below:

Output