Exercise 6: Using Packages and Modules in Go

Learn how to organize your code with packages and modules in Go.

Why Use Packages and Modules?

Packages and modules help structure your code, make it reusable, and efficiently manage dependencies.

Creating a Package in Go

A package is a collection of Go files grouped in the same directory. Here’s an example of a `mathutils` package:

// File: mathutils/mathutils.go
package mathutils

// Addition adds two numbers
func Addition(a, b int) int {
    return a + b
}

Importing and Using a Package

After creating a package, you can use it in another file:

package main

import (
    "fmt"
    "myproject/mathutils"
)

func main() {
    result := mathutils.Addition(5, 3)
    fmt.Println("Result:", result)
}

Managing Modules with `go mod`

Go uses `go mod` to manage external and internal dependencies.

go mod init myproject

The `go.mod` file identifies a Go project as a module.

Exercise Instructions

Expected Output

Result: 8

Best Practices for Packages and Modules in Go

πŸ“š Learn more about Go packages and modules:

Official Go Documentation
← Previous Exercise Next Exercise β†’

πŸš€ Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! β˜•πŸ˜Š


β˜• Buy me a coffee