go - 如何在Golang中将变量参数传递给Sprintf

标签 go slice

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

我收到以下消息:

fmt.Printf的参数中不能使用v(类型[] string)作为类型[] interface {}

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

最佳答案

是的,有可能,只需将您的分片声明为[]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/63933434/

相关文章:

go - 如何在 gorilla Mux的Get Subrouter中将特定中间件用于特定路由

reflection - 如何将 reflect.Value 转换为它的类型?

go - 如何通过 golang 或 C# 以外的其他语言将 EWS 获取项目正文传输到 PST 文件

generics - 如何为 &T 的所有可迭代对象实现一次特征(例如 Vec<T> 和 &[T])

image - Matlab DICOM 切片

memory-leaks - Golang Goroutine 泄漏

javascript - 在 HTML 页面上使用 Golang 进行实时搜索

python - python 中的扩展切片?

javascript - 按索引切片数组并插入空数组

dictionary - 如何将 map 转换为条目 slice ?