Packages

Packages

What are Packages?

Packages in Go are used to organize code into modular components. They allow for better code reuse, compartmentalization (ngăn cách), and readability. By grouping related functions into packages, Go helps in maintaining and scaling projects. A package is simply a collection of .go files in the same directory that are compiled together.

For example, in a fintech application, you can create packages like simpleinterest, compoundinterest, and loanrepayment to separate different functionalities, making the code reusable and maintainable.

Go Modules

A Go module is a collection of Go packages. Modules are essential for managing dependencies, and the go.mod file keeps track of package versions.

Creating a Go Module

To create a Go module:

1. Create a directory, e.g., learnpackage:

mkdir ~/Documents/learnpackage/        

2. Inside the learnpackage directory, run:

go mod init learnpackage        

This creates a go.mod file, where learnpackage is the module's name. This is the base path for importing any package created inside this module.

Creating a Custom Package (Simple Interest Example)

1. Create a folder simpleinterest inside learnpackage to store the package files.

2. Inside simpleinterest, create a simpleinterest.go file with the following content:

package simpleinterest

// Calculate calculates and returns the simple interest for principal p, rate r, and time t
func Calculate(p float64, r float64, t float64) float64 {
    interest := p * (r / 100) * t
    return interest
}        

3. Now, create a main.go file in the learnpackage folder with the following content:

package main

import (
    "fmt"
    "learnpackage/simpleinterest"
)

func main() {
    fmt.Println("Simple interest calculation")
    p := 5000.0
    r := 10.0
    t := 1.0
    si := simpleinterest.Calculate(p, r, t)
    fmt.Println("Simple interest is", si)
}        

Explanation:

  • Custom Package: The simpleinterest package is created to calculate the simple interest.
  • Importing Package: The main package imports learnpackage/simpleinterest and calls the Calculate function to compute the interest.
  • Running the Program: After building the project with go build, you can run the program to get the simple interest.

Output:

Simple interest calculation
Simple interest is 500        

A Bit More on go build

The go build command works within the context of the current directory, meaning you must run it from the directory containing your go.mod file (e.g., learnpackage).

You can also use go build -o fintechapp to specify a custom output binary name, like fintechapp.

Exported Names

In Go, functions or variables that start with a capital letter are exported, meaning they can be accessed outside the package. If the function Calculate was renamed to calculate (lowercase), it wouldn’t be accessible from the main package.

The init Function

Each Go package can have an init function, which is automatically executed when the package is initialized. The init function is useful for performing setup tasks or verifying conditions before the main function runs.

Example of using an init function in the simpleinterest package:

package simpleinterest

import "fmt"

func init() {
    fmt.Println("Simple interest package initialized")
}

func Calculate(p float64, r float64, t float64) float64 {
    interest := p * (r / 100) * t
    return interest
}        

Blank Identifier (_)

Go does not allow unused imports. However, if you need to import a package without using it, you can use the blank identifier (_). This can be useful when you want to initialize a package for its side effects (e.g., init functions).

Example:

package main

import (
    _ "learnpackage/simpleinterest" // Import for side effects
)

func main() {
    // main function code
}        

In this case, the simpleinterest package is imported to trigger the init function without needing to use any function or variable from it.

Summary

In this tutorial, we learned about Go packages and their role in organizing code. We created a custom package to calculate simple interest and used it in the main package. We also explored the go.mod file, init functions, exported names, and the use of the blank identifier.

Next tutorial: if else statement

To view or add a comment, sign in

More articles by Nin Tran

  • Why Microservices are Beating Monoliths in Modern Software Development

    In today’s fast-moving tech world, building software that is scalable, resilient, and easy to evolve is more important…

  • The 5 Key Scrum Ceremonies You Should Know

    In the Scrum framework, effective communication and continuous improvement are driven by five essential ceremonies: 1…

    1 Comment
  • Key Kubernetes Concepts – A Concise Overview for Engineers

    Kubernetes has become the backbone of modern cloud-native infrastructure. For teams building and scaling containerized…

  • Switch Statement

    In Go, the switch statement is a powerful tool for performing multiple comparisons against a single expression. It is…

  • Loops

    In Go, loops are used to execute a block of code repeatedly until a specified condition is met. The only loop available…

  • 🚀 How I Set Up My Mac Terminal (Every Time I Get a New Machine)

    Recently, our IT team reinstalled my Mac — which reminded me how often I end up redoing my terminal setup from scratch.…

    1 Comment
  • Object-Oriented Go: Applying OOP Principles in the Go Programming Language

    Object-Oriented Programming (OOP) has shaped the way we build software for decades. Centered around "objects" —…

  • If else statement

    What is an If Statement? In Go, an if statement checks a condition and executes a block of code if the condition…

  • Functions

    What is a Function? A function is a block of code that performs a specific task. It takes input, processes it, and…

  • Constant in Golang

    What is a Constant? Constants represent fixed values that do not change throughout the program’s execution. Examples…

Explore content categories