DEV Community

Cover image for How To Create Package in Go
Didik Tri Susanto
Didik Tri Susanto

Posted on • Originally published at blog.didiktrisusanto.dev

How To Create Package in Go

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!")
}
Enter fullscreen mode Exit fullscreen mode

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 mygopackageas package name.

git mod init github.com/didikz/mygopackage
Enter fullscreen mode Exit fullscreen mode

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

Folder 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
}
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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

Easy right?

The final main.go file 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())
}
Enter fullscreen mode Exit fullscreen mode

That's it and happy coding!

Top comments (0)