Skip to content

Structure of a Go Program

Last updated on March 28, 2019

Every single programming language has got its own syntax or structure; it’s own flavor and that’s what makes it standout. Go is no different. It’s easy and elegant in its own way, making to it fun to play with. In this article we will be talking about:

 

Go Program Structure

To understand the Go program structure, we need to have a Go program first, so let’s revisit our favorite Hello, World! program.

package main 
import "fmt" 

func main() { 
    fmt.Println("Hello, World!")
}

Every source file (a file with .go extension) has to have package declaration as its first line of code. In our hello-world.go, the first line package main, tells the compiler that this source file is going to contain the entry point for Go, which is the main function. This combination of main package declaration and main function makes it a standalone executable Go program.

In our code, we are writing to console, which is the standard output. For this to work, we import the fmt package using the import keyword. The fmt package which is short for format, comes with the Go standard library. The fmt package comes with a lot of options for writing to standard output. We will later see the syntax for importing multiple packages.

 

Running a Go Program

We can run any Go program using either go run or go build command. Using these commands, we instruct the Go compiler to compile and run Go code. To run our Hello World program we can use the go run hello-world.go command, being in the same directory as the program file.

go run hello-world.go
go run hello-world.go

We can also use the go build which will in turn generate an executable named hello-world, that can be run like any other executable.

go build
go build

If for any reason, we want to change the name of our executable then we can do so by using the go build -o <file-name> command. This will create an executable binary with specified <file-name>. For example,

$ go build -o exe  //being in the hello-world directory
$ ./exe            // running the executable 
Hello, World!

As need may arise, we may want to install our app. To do so we use the go install <package-name> command. This creates a binary executable and stores it in the $GOPATH/bin directory. So, ensure that the GOBIN is set and added to the PATH environment variable. And since we have the PATH variable set, we can run our binary from anywhere on our system.

go install hello-world
go install hello-world

 

Comments

Adding comments in our code at the right place is as important as writing a good maintainable code. In Go, comments are not just a way of adding an inline explanation to what your code does, rather it’s also a way of documenting your packages and we will see that when we talk about functions and packages.

Well, there are two ways to add comments in your code – line comments or block comments, similar to other programming languages. To add a line comment we simple start with // followed by the comment text. To add a block comment, we wrap our text between the /* and */. Here is an example of both:

// package main defines the entry point
package main 

// import the 'fmt' package from standard library
import "fmt" 

/*
    The main function is the entry point in a Go program.
    The main function does not have a return type.
    Also, it does not accept any parameters.
*/
func main() { 
    fmt.Println("Hello, World!")
}

 

What about Semicolons?

As you must have observed in the above code, we have not put a single semicolon. Because behind the scenes, Go does that for us. Like C, Go’s grammar also uses semicolon to terminate statements, but they don’t have to appear in the source code. Here is what the Go’s documentation says about it:


Like C, Go’s formal grammar uses semicolons to terminate statements, but unlike in C, those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them.
The rule is this. If the last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the tokens break continue fallthrough return ++ -- ) }

the lexer always inserts a semicolon after the token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”.
A semicolon can also be omitted immediately before a closing brace, so a statement such as tokens break continue fallthrough return ++ -- ) }

needs no semicolons.

tokens break continue fallthrough return ++ -- ) }

To read more about the internals, go ahead and spend some time with Go Docs.

 

Revisiting the code

As we learned earlier, every standalone application must have a package main declaration, and a .go file with such declaration must have a main function. This main function is the entry point for our application, as in other programming languages like C, Java, C# etc.

The difference is that in Java or C# the main function can accept arguments (string[] args), while in Go the main function does not accept any arguments. Also, the main function does not return anything.

Notice how we are importing the fmt package: import "fmt". This syntax works only when we are importing a single package. If we want to import multiple packages, then we need to group our packages in import (). Here is an example:

// importing multiple packages in Go
import (
	"context"
	"database/sql"
	"fmt"
	"log"
)

Note that we have not put a ; at the end of any imported package, since this will be done for us by the lexer.

 

Conclusion

Go has very simple program structure, which feels and reads more like C. Following the same pattern, we have main function as the entry point for our application. Go offers a convenient way of writing clean code by smartly inserting semicolons where required. We have different types of comments for logical descriptions in our code. We will later see how these comments build the documentation for our packages.

To better understand what happens behind the scenes and how we can write quality code in Go, I would highly recommend you to checkout the Effective Go page from Go docs.

 

Published inGo