Reputation: 679
Why doesnt this give a compile error, is it a bug in golang or do I miss something?
intPadded := fmt.Sprintf("%09d", "i am a string" )
fmt.Println("bah" + intPadded)
when executed it gives
bah%!d(string=i am a string)
Upvotes: 1
Views: 2256
Reputation: 166529
It's your bug. The compiler can only check that the fmt.Sprintf
arguments have the proper type; all types implement the empty interface. Use the Go vet
command.
func Sprintf(format string, a ...interface{}) string
Sprintf formats according to a format specifier and returns the resulting string.
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface.
A type implements any interface comprising any subset of its methods and may therefore implement several distinct interfaces. For instance, all types implement the empty interface:
interface{}
Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string.
Upvotes: 2
Reputation: 6545
"If an invalid argument is given for a verb, such as providing a string to %d, the generated string will contain a description of the problem" per http://golang.org/pkg/fmt/
It doesn't give a compile-time error because there is no compile-time error. fmt.Sprintf()
is defined as taking ...interface{}
for its last argument, which is valid for any sequence of types. The checking is done only at runtime.
Upvotes: 1