Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"%!s"-like error in fmt.Printf when format string is from arguments (go language)

Tags:

format

printf

go

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

like image 804
henry Avatar asked Sep 17 '25 14:09

henry


1 Answers

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.

like image 55
kubistika Avatar answered Sep 22 '25 16:09

kubistika