Behaviour of fmt during the build process

I have a use case where I’m using fmt.Sprintf in one package and importing it into another. The code builds successfully without errors, but I expected it to fail.

package a

func XYZ() {
	.....
	.....

			log.Error(fmt.Sprintf("Failed to perform operation %s, error: %s", err.Error()))
}



package b
import "a"
....

Is it true that if code complies without errros, it means the function fmt.Sprintf doesn’t check the arguments at compile time and could throw a runtime error if the number of arguments doesn’t match? This is my understading but I may be wrong.

Hello, the formatted string is not checked during comptime. But there will be no error at runtime. Instead, message will be shown:

fmt.Println(fmt.Sprintf("%s: %s", "test"))

// Output: "test: %!s(MISSING)"
1 Like

Yeah - if you run that in the playground you will see it’s go vet that catches this:

# [play]
./prog.go:8:14: fmt.Sprintf format %s reads arg #2, but call has 1 arg

Go vet failed.

test: %!s(MISSING)

Program exited.

You can read more about go vet here:

1 Like