dongli8979
dongli8979
2015-10-13 02:08
浏览 59
已采纳

Golang:可变参数

When I compile the following program

func myPrint(v ...interface{}) {
        fmt.Println("Hello", v...)
}
func main() {
    myPrint("new", "world")
}

I get a compilation error

too many arguments in call to fmt.Println

I thought v... is going to expand into 2nd, 3rd arguments and the fmt.Println would see three item variadic argument list. I thought it would be equivalent to

fmt.Println("Hello", "new", "world")

Why is it giving an error.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutangdan3588
    doutangdan3588 2015-10-13 02:20
    已采纳

    You're mis-using the variadic shorthand in your call to fmt.Println(). What you're actually sending is 2 arguments: a single string, then the slice of type interface{} expanded. The function call will not concatenate that into a single slice.

    This design will compile and run with the results you're expecting:

    func myPrint(v ...interface{}) {
        fmt.Print("Hello ")
        fmt.Println(v...)
    }
    
    func main() {
        myPrint("new", "world")
    }
    
    点赞 评论
  • dpsx99068
    dpsx99068 2015-10-13 02:26

    Try this. It prepends Hello to the variadic arguments, then prints them all at once with println.

    package main
    
    import "fmt"
    
    func myPrint(v ...interface{}) {
        a := append([]interface{}{"Hello"}, v...)   // prepend "Hello" to variadics
        fmt.Println(a...)                           // println the whole lot
    }
    func main() {
        myPrint("new", "world")
    }
    
    点赞 评论

相关推荐