Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you wrap var args in Go?

Tags:

go

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.

like image 412
Doug Avatar asked Dec 08 '22 17:12

Doug


2 Answers

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
like image 149
zzzz Avatar answered Dec 11 '22 07:12

zzzz


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

like image 27
Jeremy Wall Avatar answered Dec 11 '22 08:12

Jeremy Wall