How can I use a slice as an argument?

Hi,
I am not sure how to call it since it has different names in different languages, ruby calls it the splat operators which allows you to for example use an array of 3 elements as arguments fo a method which takes 3 arguments, is there something similar in go ?

It could look like this with a slice:

func DoSomething(a, b int){}

arr := []int{1, 2}
DoSomething( *arr )

which would result in this:
DoSomething(1, 2)

Hey @Julien_Ammous,

I believe you are referring to the ellipsis operator, which can be used in 2 ways, for example:

package main

import "fmt"

func printInts(ints ...int) {
	for _, i := range ints {
		fmt.Print(i)
	}
}

func main() {
	intsSlice := []int{1, 2, 3, 4, 5}
	printInts(intsSlice...)
}

In the function printInts, the ellipsis operator is specifying that there can be any amount of integers passed to the function, whereas when calling the printInts function, when passing instsSlice..., the ellipsis operator “unpacks” or “expands” the slice for the function.

1 Like

That’s an alternative but I suppose there is no equivalent in go for what I was looking for.

The equivalent is what @radovskyb explained above, the ellipsis operator.

1 Like

@Julien_Ammous: With “equivalent”, do you mean this hypothetic Go code (that fails):

package main

import "fmt"

func printInts(a, b, c, d, e int) {
	fmt.Println(a, b, c, d, e)
}

func main() {
	intsSlice := []int{1, 2, 3, 4, 5}
	printInts(intsSlice...). // error: not enough arguments in call to printInts
}

The error message reveals why this does not work:

tmp/sandbox345188635/main.go:11: not enough arguments in call to printInts
	have ([]int...)
	want (int, int, int, int, int)

Why do you need this Ruby feature in Go?

I don’t need it, but I was just wondering whether there was an equivalent or not.
And yes your equivalent code is correct but there is no such thing, it is fine, thanks for the answers.

@dfc the ellipsis operator also exists in Ruby, that’s not an equivalent, they are two differents things with different purposes, in one case you have a method receiving an unknown number of arguments, in the other the arguments are named and their count is fix, look at the last code christophberger wrote.

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