Calling Println with the ... operator?

For my own comprehension, I don’t understand why I can’t do:

x := []int{1,2,3}
fmt.Println(x...)

I thought it would be equivalent to:

fmt.Println(1, 2, 3)

Do I have to explicitly declare my slice with the type interface{} like this:

x := [](interface{}){1, 3, 8, 4, 2}
fmt.Println(x...)

Or is there another way with keeping my slice of int ?

Unfortunately Println wants a slice of interface{} and you have a slice of int, and these are not convertible.

https://golang.org/doc/faq#convert_slice_of_interface

1 Like

Thank you Jakob for the pointer to that FAQ entry. It’s exactly the answer I was looking for.

Therefore I have to manually convert it like this:

x := []int{1,2,3}
fmt.Println(toSliceInterface(x)...)

func toSliceInterface(p []int) []interface{} {
	s := make([]interface{}, len(p))
	for i, v := range p {
		s[i] = v
	}
	return s
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.