Go basics

The simplest structure of a Go program

Rodrigo Ancavil
2 min readAug 12, 2023

A basic program in Go should have the following structure.

Create a file called main.go (or any name with a .go extension)

package main

import "fmt"

func main() {
fmt.Println("A first program in Go!!!")
}

package: says that the program belongs to the main package.

import: will import every package needed by our program. In this case, we are importing the fmt package, which implements formatted I/O with functions (Println, Printf, Scanf, Fscanf, etc.)

func main(): it is the entry point to our code.

Running the code:

$ go run main.go

$ go build -o <name> main.go

The first command (go run <name.go>) compile and execute the program, and the second one (go build) compiles and creates an executable <name>.

How to create a project

$ mkdir myapp 
$ cd myapp
$ go mod init example/myapp

go mod init example/myapp will create the module example/myapp. A file go.mod will be created in the myapp directory. This file will contain all dependencies needed by our project.

So, we have to create the main.go file in the directory myapp; this will be the entrypoint for our application (the main part of the application)

package main

import "fmt"

func main() {
fmt.Println("Main module, entrypoint")
}

Now, we can run it.

$ go run .

Importing an external module.

To import an external module, we can do two things.

First, write the code, including the external modules we need. In this case, we want to use the external UUID module (Notice that the UUID module is on github.com).

package main

import (
"fmt"

"github.com/google/uuid"
)

func main() {
fmt.Println("Main module")

uuid := uuid.New().String()

fmt.Println("UUID :", uuid)
}

Now, execute the following command. This will import the module and configure the dependencies for the project.

$ go mod tidy

To verify, open the file go.mod

module example/myapp

go 1.20

require github.com/google/uuid v1.3.0

Another way is to import the module using get.

$ go get github.com/google/uuid

Both methods create go.sum that contains the checksums of dependencies required along with the versions.

github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=

Once we have finished our application, we can create an executable for our application.

$ go build -o myapp .

This command will create an executable considering the whole dependencies needed by the app.

You can continue with:

--

--

Rodrigo Ancavil
Rodrigo Ancavil

Written by Rodrigo Ancavil

IT Architect and Software Engineer

No responses yet