Diference between "foo ...int" and "foo []int"

Hello folks,

I just want to knw the difference between this code:

func main() {
	s := []int{1, 2, 3, 4, 5, 6, 7, 8}
	t := sumall(s)
	fmt.Println(t)
}
func sumall(x []int) int { 
	n := 0
	for _, v := range x {
		n += v
	}
	return n
}

And this one:

func main() {
	s := []int{1, 2, 3, 4, 5, 6, 7, 8}
	t := sumall( s...)
	fmt.Println(t)
}

func sumall(x ...int) int {
	n := 0
	for _, v := range x {
		n += v
	}
	return n
}

In the first one i’m passing the slice for the function “sumall” and in the second one i’m passing “s…” and in the function “x …int”.
Both return the same result, so is there a big difference by using one or the other?

thx in advance

The difference is especially important if you do not have the preallocated slice, but instead want to just call a function… Just consider how clunky the use of fmt.Printf was if we didn’t have variadic arguments…

fmt.Printf("%v %v", "foo", "bar")

# vs

fmt.Printf("%v %v", []interface{}{"foo", "bar"})

The difference is the way you can invoke the function.
The first function accepts as input a slice of int while the second one accepts a variadic number of int values.

For instance you could invoke the second as

sumall(1, 2, 3, 4)
2 Likes

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