Structure of a Simple Go program
Learn Go essentials by understanding how a Go program works and its basic structure, how to differentiate between Go programs and applications, and discover the next steps to enhance your coding journey.
Learn to Go essentials by understanding how a Go program works and its basic structure, how to differentiate between Go programs and applications, and discover the next steps to enhance your coding journey.
You'll use the minimum syntax required to write a valid Go program and learn how to format it and run it on the cloud. Get started with Go!
How Does a Go Program Work?
When you write code to create a program using Go, you must compile the code before you can run it and use it. The Go compiler generates a Go executable once it compiles your code. The Go executable has the Go runtime built in, which you can use to execute or run your Go program.
Let's break down this process in more detail:
- Compilation: The compiler translates your Go code into machine code that the computer's processor can understand.
- Linking: After compiling the individual files, the Go linker combines all the compiled code and any libraries into a single executable binary. This binary will include the Go runtime.
- The Go runtime is part of the generated executable. It handles initializing the program, managing memory, and starting a main function that serves as the entry point to your program.
- The runtime is an integral part of Go programs that provides key functionalities a program needs during its execution, such as garbage collection, concurrency, stack management, etc.
- Execution: When you execute the binary, the operating system loads the binary into memory, starts the Go runtime, and the runtime then runs the main function.
- The main function is the entry point of your Go application, so its execution represents the program doing its assigned task.
- Behind the scenes, the Go runtime interacts with the operating system to perform tasks like handling I/O operations, managing processes and threads, and dealing with file systems and network communications.
Let's see this process in action by building a simple Go program and exploring its structure in detail.
Structure of a Simple Go Program
The following code represents a minimal Go program that prints a string to the console:
package main
import "fmt"
func main() {
fmt.Println("Go, Go, Power Gophers!")
}
Let's walk through the process of building this simple Go program step by step to understand the critical components that make this valid and runnable Go code.
To build this application, you don't need to download any programs or editors: head to the Go Playground and enter your code there. In the Go Playground, use the "Format" button to make the code look nice and the "Run" button to execute it.
Go package declarations
The first statement of any Go program is a package declaration:
package name
Every Go program is made up of packages. Packages are a convenient way to organize code logically in Go. A package contains code with related functionality. For example, a package may help perform operations on strings or process input and output from the command line.
The package keyword is followed by the package name in the declaration. There are tons of standard and custom Go packages out there. However, for this simple program, we use a very special one: main.
The Go main package
Go programs start running in package main. The Go compiler creates a Go program by linking this single main package with all the packages it imports. You don't import the main package anywhere else in your application. The main package must implement a main() function that takes no arguments and returns no value. The main function within the main package is the entry point of a Go program as
As such, the most basic Go program would look something like this:
package main
func main() {
}
The program above doesn't do anything, but it's a valid Go program. The initial code snippet shows that this program should print a string to the console. You need the Println() function from the fmt package to do so.
Importing packages
The fmt package is a standard library package that implements functions that handle formatted input and output in Go. If you are familiar with C, the programming language, the fmt functions are analogous to C's printf and scanf.
You first need to import the fmt package before you can use any of its methods:
package main
import "fmt"
func main() {
}
The import declaration takes a string that uniquely identifies a package. Now, you can use any of the fmt methods within the body of the main function.
Update your code to use Println() to print a string:
package main
import "fmt"
func main() {
fmt.Println("Go, Go, Power Gophers!")
}
The Println() function in Go prints text to the screen, ending with a new line to keep everything organized.
Executing logic in Go's main function
Run your program in the Go Playground. You should see the following output in the console:
Go, Go, Power Gophers!
Program exited.
That's all there is to create a simple, valid, and functional Go program! To extend this tiny program, you can import other packages or create other functions to call within the main function to create a more complex system or application.
Go Program vs Go Application
You may have noticed that in this article so far, we have only referred to what you are building as a "Go program". But what exactly is a Go program, and why not call it a Go application?
Developers often use the terms "program" and "application" interchangeably in the context of software, but these terms can have slightly different meanings:
The "Go program" term typically refers to a set of Go source code files that perform a specific task when executing them. It's a more general term that can refer to anything developers write in Go, from a simple script that prints a string to a complex system utility. A Go program becomes an executable when you compile it.
"Go application" usually refers to a more complex and complete software product, often with a specific purpose or defined user interaction. An application often has multiple components and may include a graphical user interface, handle data processing, integrate with databases, or make network requests.
A Go application is a type of Go program, but not all Go programs are complex enough for you to consider them as applications. You can refer to simple or small pieces of code as "programs" while referring to larger, more complex software systems as "applications".
In practice, whether you call something a Go program or a Go application depends on the context in which you're discussing it and how the team working with you communicates.
Next Steps
Bootstrapping a Go program requires little syntax. Go is known for its simplicity and efficiency. As such, the structure for a Go program consists of a simple pattern:
// package declaration
// package imports
// Program logic
An excellent next step is to become familiar with the best practices around writing Go code, such as:
- Formatting: Use a tool like
gofmtto format your code automatically. - Linting: Go has several tools to lint your code, like
golintorstaticcheck. These tools help you adhere to the coding standards and identify potential issues before runtime. - Commenting: Write comments for exported functions, types, and methods. Comments should start with the name of the element they're describing and provide meaningful information about the behavior.
- Error Handling: Always check for errors where they can occur. Go does not have exceptions; it handles errors explicitly.
- Package Naming: Keep package names concise, lowercase, and free of underscores or mixed caps.
- Variable Naming: Use short, concise variable names for small scopes. Use longer, descriptive names for larger scopes.
- Concurrency: Use Go's concurrency features like goroutines and channels, but synchronize access to shared state and avoid race conditions.
Once you're comfortable with the essentials and best practices of writing Go code, you can explore more complex topics in Go, such as:
- Structs and interfaces for object-oriented programming.
- Goroutines and channels for concurrent programming.
- Working with the standard library for tasks like HTTP requests, JSON manipulation, and more.
- Writing tests using the built-in testing package.
Keep practicing and reading more about its idiomatic practices. Enjoy your journey with Go!