2014-03-30 13:05



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)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • douba4933 douba4933 7年前

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

    点赞 评论 复制链接分享
  • dongyuyi5680 dongyuyi5680 7年前

    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:


    Command vet

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

    点赞 评论 复制链接分享