我正在实现标准日志包的包装器,以创建具有各种日志级别的记录器.
我有以下界面:
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{})
}
Run Code Online (Sandbox Code Playgroud)
在实现中我有这样的东西(不是确切的代码)
func Info(format string, args ...interface{}){
msg := fmt.Sprintf(format, args...)
log.Println(msg)
}
Run Code Online (Sandbox Code Playgroud)
现在,假设我像这样调用我的库:
logger.Info("Hello %s", "World")
Run Code Online (Sandbox Code Playgroud)
我得到打印输出:"Hello%!(EXTRA string = WORLD)",而不是预期的"Hello World".如果我这样做有类似的输出
msg := fmt.Sprintf(format, args)
Run Code Online (Sandbox Code Playgroud)
这将返回"Hello World%!EXTRA [] interface {} = []".
Bop*_*reH 10
我无法重现这种行为.你确定这不是一个简单的错误,你忘了在这里展示吗?
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")
}
Run Code Online (Sandbox Code Playgroud)
打印
Hello World
Run Code Online (Sandbox Code Playgroud)
根据该fmt文件,%!(EXTRA string=WORLD)添加到你时,将额外的参数,由格式意想不到的字符串.也许您正在使用格式字符串"Hello World"而不是"Hello %s",或者传递参数两次?
错误发生在椅子和键盘之间。我混淆了以下接口:
func Print(v ...interface{})
func Printf(format string, v ...interface{})
Run Code Online (Sandbox Code Playgroud)
我的一些代码在没有格式字符串的情况下调用库。有关更详细的示例,请参见此处:http ://play.golang.org/p/Xx79qujaFp