这是我要模拟的示例函数:
package main
import "fmt"
func main() {
fmt.Println(fmt.Sprintf("Initially I want %d %s", 2, "dogs"))
fmt.Println(Sprintf2("Now I want %d %s", 2, "dogs"))
}
func Sprintf2(format string, a ...interface{}) string {
return fmt.Sprintf(format + " and %d cats", append(a, 5))
}
这是 playground 中的一个链接:https://play.golang.org/p/dHDwTlbRLDu
预期输出:
Initially I want 2 dogs
Now I want 2 dogs and 5 cats
实际输出:
Initially I want 2 dogs
Now I want [2 %!d(string=dogs) 5] %!s(MISSING) and %!d(MISSING) cats
最佳答案
您需要先将新值附加到 a
slice ,然后在调用 fmt.Sprintf
时解压 slice :
func Sprintf2(format string, a ...interface{}) string {
a = append(a, 5)
return fmt.Sprintf(format+" and %d cats", a...)
}
关于go - 如何将值附加到 ...interface{}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50216961/