2015-10-28 19:49
采纳率: 100%
浏览 917

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

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

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{}=[]".

图片转代码服务由CSDN问答提供 功能建议



  type Logger接口{
 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字符串,args ... interface {})
 Panic(fmt字符串,args ... interface {})
   \  n 


  func Info(格式字符串,args ... interface {}){\  n msg:= fmt.Sprintf(format,args ...)

现在,假设我调用了我的库 像这样:

  logger.Info(“ Hello%s”,“ World”)

打印输出:“ Hello%!(EXTRA string = WORLD)”,而不是预期的“ Hello World”。 如果我这样做,会有类似的输出

  msg:= fmt.Sprintf(format,args)

返回“ Hello World%!EXTRA [] interface {} = []””。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doujiazong0322 2015-10-28 20:03

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

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


    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 2015-10-28 20:45

    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:

    解决 无用
    打赏 举报

相关推荐 更多相似问题