Reader small image

You're reading from  Go Programming - From Beginner to Professional - Second Edition

Product typeBook
Published inMar 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781803243054
Edition2nd Edition
Languages
Right arrow
Author (1)
Samantha Coyle
Samantha Coyle
author image
Samantha Coyle

Samantha Coyle, a Software Engineer at Diagrid, specializes in Go for cloud-native developer tooling, abstracting application development challenges. Committed to Open Source, she contributes to projects like Dapr and Testcontainers. She boasts a rich history in retail computer vision solutions and successfully stabilized industrial edge use cases with testing and diverse deployments for biopharma data pipelines. Her expertise extends to being CKAD certified and reviewing Go textbooks. She is passionate about empowering early-career, diverse professionals. Samantha is in a family of gophers, and enjoys GopherCon with her brother and identical twin sister. She's a seasoned speaker, having presented at various conferences, including GopherCon.
Read more about Samantha Coyle

Right arrow

Using Go Tools

Overview

This chapter will teach you how to make use of the Go toolkit so that you can improve and build your code. It will also help you build and improve your code using Go tools and create binaries using go build. Furthermore, you’ll learn how to clean up library imports using goimports, detect suspicious constructs with go vet, and identify race conditions in your code using the Go race detector.

By the end of this chapter, you will be able to run code with go run, format code with gofmt, automatically generate documentation using go doc, and download third-party packages using go get.

Technical requirements

For this chapter, you’ll require Go version 1.21 or higher. The code for this chapter can be found at https://github.com/PacktPublishing/Go-Programming-From-Beginner-to-Professional-Second-Edition-/tree/main/Chapter20.

Introduction

In the previous chapters, you learned how to produce concurrent and well-tested code. Although Go makes the task of creating concurrent and tested code much easier compared to other languages, these tasks can be intrinsically complex. This is when learning to use tools to write better code that will simplify the complexity comes in handy.

In this chapter, you will learn about Go tools. Go comes with several tools to help you write better code. For example, in the previous chapters, you came across go build, which you used to build your code into an executable. You also came across go test, which you used to test your code. There are also a few more tools that help in different ways. For example, the goimports tool will check if you have all the import statements required for your code to work and if not, it will add them. It can also check if any of your import statements are no longer needed and remove them. While this seems like a very simple thing, it means you no...

The go build tool

The go build tool takes Go source code and compiles it so that it can be executed. When creating software, you write code in a human-readable programming language. Then, the code needs to be translated into a machine-readable format so that it can be executed. This is done by a compiler that compiles the machine instructions from the source code. To do this with Go code, you can use go build.

Exercise 20.01 – using the go build tool

In this exercise, you will learn about the go build tool. This will take your Go source code and compile it into a binary. To use it, run the go build tool on the command line while using the –o flag to specify the output file or executable name:

go build -o name_of_the_binary_to_create source_file.go

If the –o flag is omitted, the output file will be named by the package or folder that contains the source file.

Let’s get started:

  1. Create a new directory called Exercise20.01. Within that...

The go run tool

The go run tool is similar to go build in that it compiles your Go code. However, the subtle difference is that go build will output a binary file that you can execute, whereas the go run tool doesn’t create a binary file that you need to execute. It compiles the code and runs it in a single step, with no binary file output in the end. This can be useful if you want to quickly check that your code does what you expect it to do, without the need to create and run a binary file. This would be commonly used when you’re testing your code so that you can run it quickly without needing to create a binary to execute.

Exercise 20.02 – using the go run tool

In this exercise, you will learn about the go run tool. This is used as a shortcut to compile and run your code in a single step, which is useful if you want to quickly check that your code works. To use it, run the go run tool on the command line in the following format:

go run source_file.go...

The gofmt tool

The gofmt tool is used to keep your code neat and consistently styled. When working on a large software project, an important but often overlooked factor is code style. Having a consistent code style throughout your project is important for readability. When you must read someone else’s code, or even your own code months after writing it, having it in a consistent style makes you focus on the logic without much effort. Having to parse differing styles when reading code is just one more thing to worry about and leads to mistakes. To overcome this issue, Go comes with a tool to automatically format your code in a consistent way called gofmt. This means that, across your project, and even across other Go projects that use the gofmt tool, the code will be consistent. So, it will fix the formatting of the code by correcting the spacing and indentation, as well as trying to align the sections of your code.

Exercise 20.03 – using the gofmt tool

In this exercise...

The goimports tool

Another useful tool that comes with Go is goimports, which automatically adds the imports that are needed in your file. A key part of software engineering is not reinventing the wheel and reusing other people’s code. In Go, you do this by importing the libraries at the start of your file, in the import section. It can, however, be tedious to add these imports each time you need to use them. You can also accidentally leave in unused imports, which can pose a security risk. A better way to do this is to use goimports to automatically add the imports for you. It will also remove unused imports and reorder the remaining imports into alphabetical order for better readability.

Exercise 20.04 – using the goimports tool

In this exercise, you will learn how to use goimports to manage the imports in a simple Go program. When you run the goimports tool, it will output how it thinks the file should look with the imports fixed. Alternatively, you can run goimports...

The go vet tool

The go vet tool is used for static analysis of your Go code. While the Go compiler can find and inform you of mistakes you may have made, there are certain things it will miss. For this reason, the go vet tool was created. This might sound trivial, but some of these issues could go unnoticed for a long time after the code has been deployed, the most common of which is passing the wrong number of arguments when using the Printf function. It will also check for useless assignments, for example, if you set a variable and then never use that variable. Another particularly useful thing it detects is when a non-pointer interface is passed to an unmarshal function. The compiler won’t notice this as it is valid; however, the unmarshal function will be unable to write the data to the interface. This can be troublesome to debug but using the go vet tool allows you to catch it early and remediate the issue before it becomes a problem.

Exercise 20.05 – using the...

The Go race detector

The Go race detector was added to Go so that developers can detect race conditions. As we mentioned in Chapter 18, Concurrent Work, you can use goroutines to run parts of your code concurrently. However, even experienced programmers might make a mistake that allows different goroutines to access the same resource at the same time. This is called a race condition. A race condition is problematic because one goroutine can edit the resource in the middle of another reading it, meaning the resource could be corrupted. While Go has made concurrency a first-class citizen in the language, the mechanisms for concurrent code do not prevent race conditions. Also, due to the inherent nature of concurrency, a race condition might stay hidden until long after your code has been deployed. This also means they tend to be transient, making them devilishly difficult to debug and fix. This is why the Go race detector was created.

This tool works by using an algorithm that detects...

The go doc tool

The go doc tool is used to generate documentation for packages and functions in Go. An often neglected part of many software projects is their documentation. This is because it can be tedious to write and even more tedious to keep up to date. So, Go comes with a tool to automatically generate documentation for package declarations and functions in your code. You simply need to add comments to the start of functions and packages. Then, these will be picked up and combined with the function header.

This can then be shared with others to help them understand how to use your code. To generate the documentation for a package and its function, you can use the go doc tool. Documentation like this helps when you are working on a large project and other people need to make use of your code. Often, in a professional setting, different teams will be working on different parts of a program; each team will need to communicate to the other teams about what functions are available...

The go get tool

The go get tool allows you to download and use different libraries. While Go comes with a wide range of packages by default, it is dwarfed by the number of third-party packages that are available. These provide extra functionality that you can use in your code to enhance it. However, for your code to make use of these packages, you need to have them on your computer so that the compiler can include them when compiling your code. To download these packages, you can use the go get tool.

Exercise 20.08 – implementing the go get tool

In this exercise, you will learn how to download a third-party package using go get. Let’s get started:

  1. Create a new directory called Exercise20.08. Within that directory, create a new file called main.go.
  2. Run the following two commands to create the go module for this exercise:
    go mod init
    go mod tidy
  3. Add the following code to the main.go file you created:
    package main
    import (
      "fmt"
    ...

Summary

Go tools are invaluable to a programmers when they’re writing code. In this chapter, you learned about go build and how to compile your code into executables. Then, you learned how consistent neat code is important when working on a project and how you can use gofmt to automatically neaten the code for you. This can be further improved with goimports, which can remove unnecessary imports for better security and automatically add imports you may have forgotten to add yourself.

After, you looked at go vet and how it can be used to help you find any mistakes that the compiler may have missed. You also learnt how to use the Go race detector to find race conditions hidden in your code. Then, you learned how to generate documentation for your code, which makes for easier collaboration when working on larger projects. Finally, you looked at downloading third-party packages using the go get tool, which allows you to make use of numerous Go packages that are available online...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Go Programming - From Beginner to Professional - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781803243054
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Samantha Coyle

Samantha Coyle, a Software Engineer at Diagrid, specializes in Go for cloud-native developer tooling, abstracting application development challenges. Committed to Open Source, she contributes to projects like Dapr and Testcontainers. She boasts a rich history in retail computer vision solutions and successfully stabilized industrial edge use cases with testing and diverse deployments for biopharma data pipelines. Her expertise extends to being CKAD certified and reviewing Go textbooks. She is passionate about empowering early-career, diverse professionals. Samantha is in a family of gophers, and enjoys GopherCon with her brother and identical twin sister. She's a seasoned speaker, having presented at various conferences, including GopherCon.
Read more about Samantha Coyle