CodeBlanks Logo Icon CodeBlanks

go mod init

Learn to start a new Go module and the go.mod file.

go mod init

The go mod init command starts a new Go module. A module is a collection of related Go packages managed by a go.mod file.

To start a module, run go mod init example/hello in your project directory. This creates a go.mod file and writes the module path into it.

The module path usually looks like a URL: github.com/user/project. It provides uniqueness and is used when fetching dependencies with go get.

Contents of go.mod

The go.mod file is fairly simple. The first line holds the module path after the module keyword. The second line states the Go version after the go keyword.

As you add dependencies, require blocks appear; each dependency is listed with its path and version. The go.sum file keeps the hash of each dependency.

You rarely edit this file by hand; commands like go get and go mod tidy keep it up to date automatically.

Practice Module path

The command go mod init example.com/merhaba produces the line module example.com/merhaba. Parse this line with strings.CutPrefix and print the module path: yol, ok := strings.CutPrefix("module example.com/merhaba", "module ").

Starter code

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    yol, ok := strings.CutPrefix("module example.com/merhaba", "module ")
    fmt.Println(yol, ok)
}

Expected output

example.com/merhaba true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does go mod init produce?

  • A binary file
  • A main.go file
  • A README.md file
  • A go.mod file Correct answer

Explanation: go mod init creates the go.mod file.

2 Module declaration

Question
The first line of go.mod is:
____ example/hello
Answer
The first line of go.mod is:
module example/hello

Explanation: the module keyword starts the module path.

3 Match the module parts

Term Meaning
module Module path
go Go version
require Dependency
go.sum Hash store

All lessons in Beginner