首页 > 解决方案 > 如何将值附加到 ...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) 猫

标签: gointerface

解决方案


您需要先将新值附加到a切片,然后在调用时解包切片fmt.Sprintf

func Sprintf2(format string, a ...interface{}) string {
    a = append(a, 5)
    return fmt.Sprintf(format+" and %d cats", a...)
}

https://play.golang.org/p/YRWzAT2Yxm_q


推荐阅读