将变量参数传递给 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中文网其他相关文章!