How do you port var args to Go?

According to several groups, 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 we get "Hello World 10" and "10 Hello", but it is not. Instead, it gives:

 ! 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) 

That is, passing [] the interface {} to a function that takes ... interface {} as an argument does not extend the argument and instead simply passes it as a value. The first% s extends the interface [] {} in the string and further arguments are not processed.

I am sure that there should be many situations when it is necessary during registration; but I cannot find working examples of how to do this.

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

+4
source share
2 answers

I do not think the OP program should "work." Perhaps 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 
+9
source

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

+3
source

All Articles