tests for variadic functions

556 views
Skip to first unread message

Alex Dvoretskiy

unread,
May 23, 2018, 7:09:01 PM5/23/18
to golang-nuts
How do you write test for variadic functions?

For example I have function:

func max(vals ...int) int {
m := 0
for _, v := range vals {
if v > m {
m = v
}
return m
}


and how to write a few tests for it? I can't put vals ...int
in struct


package main

import (
"testing"
)

func TestMax(t *testing.T) {
var tests = []struct {
vals ...int
want int
}{
{[]int{1,2,3}, 3},
{[]int{-1,0}, -1},
{[]int{0}, 0},
}

for _, test := range tests {
if got := max(test.vals); got !=test.want {
t.Errorf("max(%d) = %d", test.vals, got)
}
}

}

Alex Dvoretskiy

unread,
May 23, 2018, 7:15:12 PM5/23/18
to golang-nuts
I got it!

max(test.vals...)

Caleb Spare

unread,
May 23, 2018, 7:15:14 PM5/23/18
to advore...@gmail.com, golang-nuts
The struct field should be vals []int and then you'd call max(test.vals...).​

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Josh Humphries

unread,
May 23, 2018, 7:20:55 PM5/23/18
to Alex Dvoretskiy, golang-nuts
The syntax you are looking for is:

   max(test.vals...) 

The ellipsis indicates that the var args are the contents of the slice, as opposed to trying to pass the slice as if it were just a single element of the var args.

----
Josh Humphries
jh...@bluegosling.com

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages