mixing “exploded” slices and regular parameters in variadic functions

后端 未结 3 803
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 02:58

I\'m wondering why it\'s not possible to do the following in go:

func main() {
    stuff := []string{\"baz\", \"bla\"}
    foo(\"bar\", stuff...)
}

func foo         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-30 03:21

    The specification on this is at the "Passing arguments to ... parameters":

    If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T.
    If f is invoked with no actual arguments for p, the value passed to p is nil.
    Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T.

    In your case, where stuff... works:

    If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

    But "bar", stuff... doesn't match either case specified above.

    T, []T doesn't match f([]T).

提交回复
热议问题