dongzichan2886
2015-06-02 06:08
浏览 317
已采纳

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

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

I got the following message:

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
", s[1], s[2], s[3])  

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

图片转代码服务由CSDN问答提供 功能建议

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

我收到以下消息:

\ n

在fmt.Printf

  s的参数中不能使用v(类型[]字符串)作为类型[] interface {}  ] string {“ a”,“ b”,“ c”,“ d”} // regexp.FindStringSubmatch()
fmt.Printf(“%5s%4s%3s 
”,s [1],s的结果 [2],s [3])
 
v:= s [1:] 
fmt.Printf(“%5s%4s%3s 
”,v ...)
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duancao2082 2015-06-02 06:15
    已采纳

    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)
    

    So this will work:

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

    Output (Go Playground):

    b    c   d
    b    c   d
    

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

    Type converting slices of interfaces in go

    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
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题