4

According to several groups posts, the following code should work:

package main import "fmt" func demo(format string, args ...interface{}) { var count = len(args) for i := 0; i < count; i++ { fmt.Printf("! %s\n", args[i]) } fmt.Printf("%+v\n", format) fmt.Printf("%+v\n", args) fmt.Printf(format, args) fmt.Printf("\n") } func main() { demo("%s %d", "Hello World", 10) fmt.Printf("\n\n") demo("%d %s", 10, "Hello") } 

And yield "Hello World 10" and "10 Hello", but it does not. Instead it yields:

! Hello World ! %!s(int=10) %s %d [Hello World 10] [Hello World %!s(int=10)] %d(MISSING) ! %!s(int=10) ! Hello %d %s [10 Hello] [10 %!d(string=Hello)] %s(MISSING) 

Which is to say that passing []interface{} to a function that takes ...interface{} as an argument does not expand the argument and instead simply passes it as the value. The first %s expands the []interface{} into a string, and no further arguments are processed.

I'm sure there must be lots of situations where this is required in logging; but I can't find any working examples of how to do it.

This is basically the 'vprintf' family of functions in C.

2 Answers 2

10

I don't think the OP program should "work". Maybe this was intended instead(?):

package main import "fmt" func demo(format string, args ...interface{}) { fmt.Printf(format, args...) } func main() { demo("%s %d\n\n", "Hello World", 10) demo("%d %s", 10, "Hello") } 

(Also here


Output:

Hello World 10 10 Hello 
Sign up to request clarification or add additional context in comments.

2 Comments

ah, thank you. For the next person who can't find this, it's hidden here as a note in the spec: golang.org/ref/spec#Passing_arguments_to_..._parameters
@Doug, this is also explained in "Effective Go" which seems to be a must-read for anyone new to the language.
4

fmt.Printf(format, args...) should do what you want I think.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.