Knaph

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, -l

Three things it does that gofmt won't:

  1. 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.
  2. Adds imports for packages you reference but never imported.
  3. Groups the standard library separately from everything else.

Here strings is imported but unused, and os is used but missing:

Before goimports
package main
 
import (
	"strings"
	"fmt"
)
 
func main() {
	fmt.Fprintln(os.Stdout, "hello")
}
After goimports
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:

Before goimports
import (
	"github.com/google/uuid"
	"fmt"
	"net/http"
)
After goimports
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.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude