0
0
Goprogramming~5 mins

Creating custom packages in Go

Choose your learning style9 modes available
Introduction

Custom packages help you organize your Go code into reusable parts. This makes your programs cleaner and easier to manage.

You want to reuse code in different programs without copying it.
Your program is getting big and you want to split it into smaller files.
You want to share your code with others as a library.
You want to keep related functions and types together.
You want to avoid name conflicts by grouping code logically.
Syntax
Go
package packagename

// Exported functions or types start with uppercase
func ExportedFunction() {
    // code
}

func unexportedFunction() {
    // code
}

The first line declares the package name.

Functions or types starting with uppercase letters are visible outside the package.

Examples
This package named mathutils has a function Add that adds two numbers.
Go
package mathutils

func Add(a int, b int) int {
    return a + b
}
This greetings package has a function Hello that returns a greeting message.
Go
package greetings

func Hello(name string) string {
    return "Hello, " + name
}
Sample Program

This program uses a custom package mypkg that has Add and Hello functions. It prints the sum and a greeting.

Go
package main

import (
    "fmt"
    "example.com/mypkg"
)

func main() {
    sum := mypkg.Add(3, 4)
    greeting := mypkg.Hello("Alice")
    fmt.Println("Sum:", sum)
    fmt.Println(greeting)
}
OutputSuccess
Important Notes

To use your custom package, it must be in your Go workspace or module.

Use go mod init to create a module and manage packages easily.

Package names should be short and meaningful.

Summary

Custom packages organize code into reusable parts.

Use uppercase names to export functions or types.

Import your package to use its functions in other files.