How To Create Package in Go

Photo by Chinmay B on Unsplash

How To Create Package in Go

Learn how to create a package using Go programming language

For reusable purpose, package is a good start to manage your Go codes because we can import and use it to our program.

Lets create a simple main file to begin with

package main

import "fmt"

func main() {
   fmt.Println("hello world!")
}

It's a simple hello world program that printed out hello world string when we run go run main.go .

Now lets initiate a package with creating the module first. Commonly it's using a git repository even we have no plan to push it to any repository out there. In this example I will use my own Github repository and use mygopackage as package name.

git mod init github.com/didikz/mygopackage

Then create a subdirectory, for example I use models and create a user.go inside of it. The structure should be looks like this

go package structure

Inside user.go I would simple create a struct and a receiver that could be imported later in the main.go . I also set package name following the current directory name as models

package models

type User struct {
    Id        int
    FirstName string
    LastName  string
    Address   string
}

func (user *User) GetName() string {
    return user.FirstName + " " + user.LastName
}

Get back to main.go and now we can try to import the package and use the defined struct. Use the module name initiated before along with the package name.

import "github.com/didikz/mygopackage/models"

Now to use the user model from the package we can write like this

var user models.User
user.Id = 1
user.FirstName = "Didik"
user.LastName = "Tri Susanto"
user.Address = "Malang"

// or alternatively
user := models.User{Id: 1, FirstName: "Didik", LastName: "Tri Susanto", Address: "Malang"}

fmt.Println(user.GetName())

All set. Next, If we run go run main.go then it should printed out Didik Tri Susanto

Easy right?

The final main.go class now should be like this

package main

import (
    "fmt"

    "github.com/didikz/mygopackage/models"
)

func main() {
    user := models.User{Id: 1, FirstName: "Didik", LastName: "Tri Susanto", Address: "Malang"}
    fmt.Println(user.GetName())
}

That's it and happy coding!