Golang Base
TutorilasCreate a module

Create a Go module

This tutorial introduces fundamental features of Go modules. If you’re new to Go, it’s recommended to complete the Get started with Go tutorial first, which covers the go command, Go modules, and basic Go code execution.

In this tutorial, you’ll create two modules:

  1. A library module intended for reuse by other libraries or applications.
  2. A caller application module that uses the library.

The tutorial includes seven parts, each illustrating a distinct aspect of Go’s module system:

  1. Create a module — Write a small module with functions callable from other modules.
  2. Call your code from another module — Import and use your new module.
  3. Return and handle an error — Add basic error handling.
  4. Return a random greeting — Work with slices (dynamic arrays).
  5. Return greetings for multiple people — Use maps for key/value storage.
  6. Add a test — Leverage Go’s built-in unit testing.
  7. Compile and install the application — Build and install your application locally.

Prerequisites

  • Some programming experience (functions, loops, arrays).
  • A code editor. Popular choices include VS Code (free), GoLand (paid), and Vim (free).
  • A command terminal (works on Linux, Mac, PowerShell, or Command Prompt on Windows).

1. Start a module that others can use

A module in Go groups related packages under a single dependency unit. It specifies:

  • The Go version supported
  • Module dependencies

As the module evolves, updates can be published for others to use.

Procedure:

  1. Open a terminal and navigate to your home directory:

    • On Linux/Mac:

      cd
    • On Windows:

      cd %HOMEPATH%
  2. Create and enter a directory for your module:

    mkdir greetings
    cd greetings
  3. Initialize a new module. Use a module path (e.g., example.com/greetings) that corresponds to a repository path if you plan to publish it:

    go mod init example.com/greetings

    This creates a go.mod file with the module name and supported Go version.

  4. In your editor, create a file named greetings.go and insert:

    package greetings
    
    import "fmt"
    
    // Hello returns a greeting for the named person.
    func Hello(name string) string {
        message := fmt.Sprintf("Hi, %v. Welcome!", name)
        return message
    }

    This defines a greetings package with an exported Hello function.


[Next Steps]

Continue with the remaining parts of the tutorial as listed, such as calling your module from another module, adding error handling and tests, and finally compiling and installing your application.

On this page