你如何在Go中包装var args?

Dou*_*oug 4 go

根据几个小组的帖子,以下代码应该工作:

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")
}
Run Code Online (Sandbox Code Playgroud)

并且产生"Hello World 10"和"10 Hello",但它没有.相反,它产生:

! 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)
Run Code Online (Sandbox Code Playgroud)

也就是说将[] interface {}传递给以...接口{}为参数的函数不会扩展参数,而只是将其作为值传递.第一个%s将[] interface {}扩展为一个字符串,并且不再处理其他参数.

我确信必须有很多情况需要记录; 但我找不到任何有关如何做的工作实例.

这基本上是C语言中的'vprintf'系列函数.

zzz*_*zzz 10

我不认为OP计划应该"有效".也许这是打算(?):

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")
}
Run Code Online (Sandbox Code Playgroud)

(也在这里


输出:

Hello World 10

10 Hello
Run Code Online (Sandbox Code Playgroud)