goimports
goimports does everything gofmt does, and then fixes your imports. Install it — this is what the PATH lesson was for:
go install golang.org/x/tools/cmd/goimports@latest
goimports -d main.go # same flags as gofmt: -d, -w, -lThree things it does that gofmt won't:
- Removes imports you aren't using. Not tidying — an unused import is a compile error in Go, so this is the difference between a file that builds and one that doesn't.
- Adds imports for packages you reference but never imported.
- Groups the standard library separately from everything else.
Here strings is imported but unused, and os is used but missing:
package main
import (
"strings"
"fmt"
)
func main() {
fmt.Fprintln(os.Stdout, "hello")
}package main
import (
"fmt"
"os"
)
func main() {
fmt.Fprintln(os.Stdout, "hello")
}Plain gofmt on that same file sorts the two lines into "fmt", "strings" and stops. The unused import stays, os is still missing, and it still doesn't compile. Sorting is a style fix; adding and removing is a correctness fix.
The grouping rule shows up once you have an outside dependency:
import (
"github.com/google/uuid"
"fmt"
"net/http"
)import (
"fmt"
"net/http"
"github.com/google/uuid"
)Standard library first, a blank line, then everything else. You'll see this shape in every Go codebase and never have to maintain it by hand.
goimports is a superset of gofmt, so it's the one to enable as format-on-save in your editor. One caveat: when a name is ambiguous — rand could be math/rand or crypto/rand — it has to guess, and occasionally guesses wrong.