Go build vs go test

I am a newbie to go. Can someone explain why “go build” does not catch the compile error in the below code while “go test” catches it.

package main

import (
“fmt”
)

func main() {
i := 10
fmt.Println("%d", i)
}

go test
./hello_world.go:9:2: Println call has possible formatting directive %d

This error is expected. However, “go build” does not give any errors.
I would have expected “go test” to do a “go build” first and then run tests (in this
case there are no tests).

My question isn’t related to running tests. Q is why “go build” is not catching the obvious compile warning in the above code block.

First, let’s quote that code properly in the forum:

package main

import (
        "fmt"
)

func main() {
        i := 10
        fmt.Println("%d", i)
}

And then also put it in the Go Playground:

https://play.golang.org/p/9fLRBaLqojx

Click on the Run button there, and you will see the same error you got from running go test. That is because the Go Playground runs go vet before compiling the code.

So does go test. You can disable that using the -vet=off option:

go test -vet=off main.go

You can run go vet by itself to just get the warning.

And about the warning, you probably meant either

fmt.Println(i)

or

fmt.Printf("%d\n",i)
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.