doubu8643
doubu8643
采纳率100%
2015-10-28 19:49

Golang:fmt,可变参数和%!(EXTRA type = value)错误

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

I'm implementing a wrapper around the standard log package to make a logger with various log levels.

I have the following interface:

type Logger interface {
  Trace(fmt string, args ...interface{})
  Debug(fmt string, args ...interface{})
  Info(fmt string, args ...interface{})
  Warn(fmt string, args ...interface{})
  Error(fmt string, args ...interface{})
  Fatal(fmt string, args ...interface{})
  Panic(fmt string, args ...interface{})
}

In the implementation I have something like this (not the exact code)

func Info(format string, args ...interface{}){
  msg := fmt.Sprintf(format, args...)
  log.Println(msg)
}

Now, assume I call my library like this:

logger.Info("Hello %s", "World")

I get the printout: "Hello %!(EXTRA string=WORLD)", instead of the expected "Hello World". There a similar output if I do

msg := fmt.Sprintf(format, args)

This returns "Hello World%!EXTRA []interface{}=[]".

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doujiazong0322 doujiazong0322 6年前

    I can't reproduce this behavior. Are you sure it's not a simple error that you forgot to show here?

    https://play.golang.org/p/-jtmll17Xj

    package main
    
    import "fmt"
    
    func Info(format string, args ...interface{}){
        msg := fmt.Sprintf(format, args...)
        fmt.Print(msg)
    }
    
    func main() {
        Info("Hello %s", "World")
    }
    

    Prints

    Hello World
    

    According to the fmt docs, %!(EXTRA string=WORLD) is added to the string when you pass extra parameters, unexpected by the format. Maybe you are using the format string "Hello World" instead of "Hello %s", or passing the argument twice?

    点赞 评论 复制链接分享
  • doujing5937 doujing5937 6年前

    The error was between the chair and keyboard. I mixed up the following interfaces:

    func Print(v ...interface{})
    func Printf(format string, v ...interface{})
    

    Some of my code was calling the library without a format string.See here for a more detailed example: http://play.golang.org/p/Xx79qujaFp

    点赞 评论 复制链接分享

为你推荐