Anatomy of a Go Program

Vignesh Muthukumaran - Jun 15 '22 - - Dev Community

I recently started learning Go after going through a lot of articles talking about all the awesome features it has. Here, I will try to break down a simple Go program that prints a line to understand the anatomy of a Go program.

package main

import "fmt"

func main(){
    fmt.Println("Hi there!")
}
Enter fullscreen mode Exit fullscreen mode

First, let's understand how to run this program. The simple command below will run the program(Assuming the file is named main.go).

go run main.go
Enter fullscreen mode Exit fullscreen mode

The Go CLI has a lot of other options as well. Let's just have a look at a few frequently used ones.

Command Function
go build Compiles go source code
go run Compiles and executes the go source code
go fmt Formats all code in the current directory
go install Compiles and installs a package
go get Downloads source code of other package
go test Run test cases associated with the project

Go Packages

So, lets start with package main.

A package is a collection of common source code files. A package can have many related files. The only requirement is that every file should declare the package it belongs to in the first line.

But, why to call our package main?

There are 2 types of packages in Go, they are

  1. Executable - Generates a executable file
  2. Reusable - Generates Libraries, reusable code

The name of the package main makes it an executable package. If we had used any other name, it wouldn't have been an executable package. An executable package automatically executes the main function inside it. main here is a key word. Main package should have a main function. Also, if we build other packages, it wouldn't result in a executable file.

Import

Now, let's look at import "fmt"

import is used to make the functionality available in the library package to the current program we are executing.

fmt is a standard library package available with Go. It implements formatted I/O functions similar to C's printf and scanf.

We can get a list of all the packages available in Go at (https://pkg.go.dev/std).

Go Functions

Functions are declared with the key word func. The syntax is as follows,

func <name of function> (<comma seperated arguments>) {
    <body of the function>
}
Enter fullscreen mode Exit fullscreen mode

Structure of a Go program

All Go files follow the same pattern.

  • Package Declaration
  • Import statements
  • Function definitions

Along this article, I hope you got a grip on the basics of Go. I will write a few more articles and will get into Go routines and all the powerful features in Go. Happy Coding!

. . . . . . . . . . . . . . . . . . .