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

编程入门 行业动态 更新时间:2024-10-24 14:21:57
本文介绍了如何在Golang中将变量参数传递给Sprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm lazy, want to pass many variables to Printf function, is it possible? (The sample code is simplified as 3 parameters, I require more than 10 parameters).

我收到以下消息:

在fmt.Printf的参数中不能将v(类型[]字符串)用作类型[] interface {}

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

推荐答案

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

Yes, it is possible, just declare your slice to be of type []interface{} because that's what Printf() expects. Printf() signature:

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

输出(进入游乐场):

b c d b c d

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

[]interface{} and []string are not convertible. See this question+answers for more details:

在接口中进行类型转换的切片

Type converting slices of interfaces in go

如果您已经有[]string或使用了返回[]string的函数,则必须手动将其转换为[]interface{},如下所示:

If you already have a []string or you use a function which returns a []string, you have to manually convert it to []interface{}, like this:

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

更多推荐

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

本文发布于:2023-11-23 19:41:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   变量   参数   如何在   Sprintf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!