dougekui1518 2018-05-07 14:47
浏览 39
已采纳

如何将值附加到…interface {}?

Here's a sample function I want to emulate:

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))
}

here's a link in playground: https://play.golang.org/p/dHDwTlbRLDu

expected output:

Initially I want 2 dogs
Now I want 2 dogs and 5 cats

actual output:

Initially I want 2 dogs
Now I want [2 %!d(string=dogs) 5] %!s(MISSING) and %!d(MISSING) cats

  • 写回答

1条回答 默认 最新

  • dpfps86064 2018-05-07 15:26
    关注

    You need to first append your new value to the a slice, and then unpack the slice when calling 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?