首页  >  文章  >  后端开发  >  如何在 Go 中将数组或切片参数传递给 Sprintf?

如何在 Go 中将数组或切片参数传递给 Sprintf?

Patricia Arquette
Patricia Arquette原创
2024-10-27 20:30:02987浏览

How to Pass Array or Slice Parameters to Sprintf in Go?

将变量参数传递给 Go 中的 Sprintf

Go 中的 Printf 函数允许使用指定的格式字符串格式化和打印输出,后跟可变数量的参数。但是,如果您希望传递数组或值切片作为参数,则可能会遇到类型错误。

考虑以下示例:

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

运行此代码会产生错误:

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

要解决此问题,您必须将切片声明为 []interface{} 类型。这是因为 Printf 需要该类型的参数。

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

另一个选项是在将 []string 传递给 Printf 之前手动将其转换为 []interface{}。

<code class="go">ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}</code>

使用这种方法允许您将 is 切片作为变量参数传递给 Printf。

以上是如何在 Go 中将数组或切片参数传递给 Sprintf?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn