doukefu1361 2018-09-22 11:29
浏览 294
已采纳

当格式字符串来自自变量(语言)时,fmt.Printf中出现类似“%!s”的错误

just see the code:(so simple that I can't believe myself)

package log

import "fmt"

func P(format string,a ...interface{}){
    fmt.Printf(format,a)
}

when called somewhere like this :

log.P("%s,%s,%d","","",0)

I got error:

[  %!s(int=0)],%!s(MISSING),%!d(MISSING)

BUT if I call fmt.Printf directly like this:

fmt.Printf("%s,%s,%d","","",0)

It works perfectly,just perfectly (of course,as basic use of fmt).

So the Question is:

Why log.P not work??

FYI:

I believe it's pretty simple ,but I just can't find an answer by google, never ever someone dropped in the hell ?

Or maybe I just dont know how to ask,so I put pure code above.

Or just I'm a super fool this time?

I signed up stackoverflow today for an answer to this. Let me know what's wrong with me. As soon...

  • 写回答

2条回答 默认 最新

  • doujing5435 2018-09-22 12:09
    关注

    It is just a little mistake. You are calling fmt.Printf with a as a single argument, while it is not. You need to pass it as a variadic argument.

    package main
    
    import (
        "fmt"
    )
    
    func P(format string, a ...interface{}) {
        fmt.Printf(format, a)
    }
    
    func P2(format string, a ...interface{}) {
        fmt.Printf(format, a...)
    }
    
    func main() {
        P("%s,%s,%d", "", "", 0)
        fmt.Println()
        P2("%s,%s,%d", "hello", "world", 0)
    }
    

    You can read about variadic parameters here.

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

报告相同问题?

悬赏问题

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