Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Structure of a Go Program

DZone's Guide to

Structure of a Go Program

Go is quickly becoming one of the more popular programming languages out there. Read on to learn how to set up your own Go application.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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:

  • A Go program structure.
  • Running a Go program.
  • Comments in Go.
  • Semicolons.
  • Revisiting the code.

Go Program Structure

To understand a Go program's 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 a .go extension) has to have a package declaration as its file line of code. In our hello-world.go file, 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 the main package declaration and the main function makes it a standalone, executable Go program.

In our code, we are writing to the 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 the go run or go build command. Using these commands, we instruct the Go compiler to compile and run our 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 command, 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 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 APIs and we will see that when we talk about functions.

Well, there are two ways to add comments in your code – line comments or block comments. To add a line comment, we simply start with //, followed by the commented out text. To add a block comment, we wrap our text between the /* and */ symbols. 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 in our code. Well, that's because behind the scenes Go does that for you. Like C, Go’s grammar also uses semicolons to terminate statements, but they don’t have to appear in the source code. Here is what the Go 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 astokens break continue fallthrough return ++ -- ) }

needs no semicolons.

tokens break continue fallthrough return ++ -- ) }

To read more about the internals, go ahead spend some time with the 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 a very simple program structure, which feels and reads more like C. Following the same pattern, we have the 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 checkout the Effective Go page from the Go docs.

Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.

Topics:
web dev ,go ,golang ,golang tutorials

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}