문제

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)
도움이 되었습니까?

해결책 2

"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.

다른 팁

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

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

Interface types

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{}

Command vet

Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top