Golang:可变参数

huangapple go评论81阅读模式
英文:

Golang : Variable argument

问题

当我编译以下程序时:

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

我得到一个编译错误:

调用 fmt.Println 时参数过多

我以为 v... 会展开成第二个和第三个参数,然后 fmt.Println 会看到一个包含三个项目的可变参数列表。我以为这等同于:

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

为什么会出现错误?

英文:

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.

答案1

得分: 6

试试这个。它在可变参数前面添加了"Hello",然后使用println一次性打印它们。

package main

import "fmt"

func myPrint(v ...interface{}) {
    a := append([]interface{}{"Hello"}, v...)   // 在可变参数前面添加"Hello"
    fmt.Println(a...)                           // 一次性打印全部内容
}

func main() {
    myPrint("new", "world")
}
英文:

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")
}

答案2

得分: 2

你在调用fmt.Println()时误用了可变参数的简写方式。实际上,你发送的是两个参数:一个字符串,然后是展开的interface{}类型的切片。函数调用不会将它们连接成一个单独的切片。

以下是可以编译和运行,并得到你期望结果的设计:

func myPrint(v ...interface{}) {
    fmt.Print("Hello ")
    fmt.Println(v...)
}

func main() {
    myPrint("new", "world")
}
英文:

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")
}

huangapple
  • 本文由 发表于 2015年10月13日 10:08:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/33092994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定