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...