0
0
GoHow-ToBeginner · 4 min read

How to Organize Packages in Go: Best Practices and Examples

In Go, organize code by grouping related functions and types into packages inside separate folders. Use clear, concise package names and keep each package focused on a single responsibility to make your code easy to understand and maintain.
📐

Syntax

In Go, a package is declared at the top of each source file using the package keyword. Files in the same folder should share the same package name. Import other packages using the import statement.

  • package name: defines the package for the file.
  • folder: groups files of the same package.
  • import: brings in other packages to use their exported code.
go
package mathutils

// Add returns the sum of two integers
func Add(a int, b int) int {
    return a + b
}
💻

Example

This example shows a simple project with two packages: mathutils for math functions and main to use them. Each package is in its own folder with clear names.

go
mathutils/mathutils.go
package mathutils

func Add(a int, b int) int {
    return a + b
}

main.go
package main

import (
    "fmt"
    "yourmodule/mathutils"
)

func main() {
    sum := mathutils.Add(3, 4)
    fmt.Println("Sum:", sum)
}
Output
Sum: 7
⚠️

Common Pitfalls

Common mistakes include:

  • Using package names that are too generic or long, making code unclear.
  • Putting unrelated code in the same package, which makes maintenance hard.
  • Using main package for all code instead of separating reusable logic.
  • Not organizing packages in folders matching their names.
go
/* Wrong: unrelated functions in one package */
package utils

import "fmt"

func Add(a, b int) int { return a + b }

func PrintMessage(msg string) { fmt.Println(msg) }

/* Right: separate packages for math and printing */

// mathutils/mathutils.go
package mathutils

func Add(a, b int) int { return a + b }

// printer/printer.go
package printer

import "fmt"

func PrintMessage(msg string) { fmt.Println(msg) }
📊

Quick Reference

  • Use short, meaningful package names (e.g., mathutils, printer).
  • Keep one responsibility per package.
  • Place each package in its own folder named after the package.
  • Export only necessary functions/types by capitalizing their names.
  • Import packages with clear paths relative to your module.

Key Takeaways

Group related code into packages placed in folders named after the package.
Use clear, concise package names that reflect their purpose.
Keep each package focused on a single responsibility for easier maintenance.
Export only what is needed by capitalizing names of functions and types.
Avoid mixing unrelated code in the same package to keep code clean.