doubu8643 2015-10-28 19:49 采纳率: 100%
浏览 1771
已采纳

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

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制