gpt4 book ai didi

go - 如何在golang中将可变参数传递给Sprintf

转载 作者:IT王子 更新时间:2023-10-29 00:56:14 26 4
gpt4 key购买 nike

我比较懒,想传很多变量给Printf函数,可以吗?(示例代码简化为3个参数,我需要10多个参数)。

我收到以下消息:

cannot use v (type []string) as type []interface {} in argument to fmt.Printf

s := []string{"a", "b", "c", "d"}  // Result from regexp.FindStringSubmatch()
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)

最佳答案

是的,这是可能的,只需将您的 slice 声明为 []interface{} 类型,因为这就是 Printf()期望。 Printf() 签名:

func Printf(format string, a ...interface{}) (n int, err error)

所以这会起作用:

s := []interface{}{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)

输出(Go Playground):

b    c   d
b c d

[]interface{}[]string 不可转换。有关详细信息,请参阅此问题+答案:

Type converting slices of interfaces in go

如果你已经有了一个[]string或者你使用了一个返回[]string的函数,你必须手动将它转换成[]interface {},像这样:

ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
is[i] = v
}

关于go - 如何在golang中将可变参数传递给Sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30588581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com