Drills — make gofmt and go vet silent
This lesson's drills aren't "write a function" — they're "make the tools go quiet." Each one is a small piece of code with something wrong. Your job: fix it until gofmt -l . prints nothing and go vet ./... prints nothing, and the names read like Go. Try each before looking.
1 (easy) — a name in the wrong style. This works, but it isn't Go:
func pages_per_day(total int, days int) int {
return total / days
}
Go uses MixedCaps, not underscores. Rename it:
func pagesPerDay(total int, days int) int {
return total / days
}
No tool flags an underscore name — but every Go reader will. Convention is the point.
2 (easy) — a comment that says nothing. A doc comment explains what and for whom, and starts with the function's name:
// this function does the printing
func listItems(items []string) { /* ... */ }
// listItems prints every item, one per line.
func listItems(items []string) { /* ... */ }
"this function does the printing" just restates that a function exists. The fixed version tells a reader what they get.
3 (medium) — a bug gofmt can't see but go vet can. This compiles and is perfectly formatted:
func show(title string) {
fmt.Printf("%d\n", title)
}
Run go vet ./...:
fmt.Printf format %d has arg title of wrong type string
%d is for integers; title is a string. That mismatch prints garbage at runtime, and vet catches it before you ship. The fix is %s:
fmt.Printf("%s\n", title)
4 (medium) — the error that stops the build. This won't even run:
import (
"fmt"
"strconv"
)
func main() {
fmt.Println("hi")
}
"strconv" imported and not used
In Go an unused import is a compile error, not a warning — unused code misleads the reader. Delete the "strconv" line and it builds. (Same rule bites unused variables.)
5 (harder) — clean it all up. This one has three problems at once — a non-Go name, no doc comment, and something go vet will flag. Make every tool silent:
func Print_all(items []string) {
for _, s := range items {
fmt.Println(s)
}
return
fmt.Println("done")
}
go vet reports unreachable code — the fmt.Println("done") after return can never run. Fix the name to MixedCaps, add a doc comment, and delete the dead line:
// printAll prints every item, one per line.
func printAll(items []string) {
for _, s := range items {
fmt.Println(s)
}
}
Now gofmt -l . is empty, go vet ./... is empty, and the name reads like Go.
Tip. This is the lesson's Verify: not program output, but two silent tools. Build the habit now —
gofmt -w . && go vet ./...before every submission. In the final project, a clean run of both is a graded checklist item.