go - 如何将值附加到 ...interface{}?
问题描述
这是我要模拟的示例函数:
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))
}
这是操场上的链接:https: //play.golang.org/p/dHDwTlbRLDu
预期输出:
最初我想要 2 只狗
现在我想要 2 只狗和 5 只猫
实际输出:
最初我想要 2 只狗
现在我想要 [2 %!d(string=dogs) 5] %!s(MISSING) 和 %!d(MISSING) 猫
解决方案
您需要先将新值附加到a
切片,然后在调用时解包切片fmt.Sprintf
:
func Sprintf2(format string, a ...interface{}) string {
a = append(a, 5)
return fmt.Sprintf(format+" and %d cats", a...)
}
推荐阅读
- javascript - 如何显示目标模式?
- c - atomic_inc_return() 是否保证原子返回值?
- android - 我正在运行条形码扫描仪和二维码扫描仪,但在尝试构建到我的设备时出现 XML 重复错误
- python - QuerySet.count() 如何返回非零值但 list(QuerySet.all()) 产生一个空列表?
- css - 引导表 td 不遵守我的宽度设置
- haskell - 无法定义采用 Int 和 Float 的函数
- python - 不同数据大小的 Matplotlib / Seaborn 小提琴图
- javascript - 如何通过在父母上添加点击事件来阅读孩子?
- html - 在反应容器中自动集中固定宽度值项
- symfony - 用户注意事项:未找到必需的@OA\PathItem():symfony 4