Reputation: 2135
I am trying to test a basic sum function with a table test. Here is the function:
func Sum(nums []int) int {
sum := 0
for _, n := range nums {
sum += n
}
return sum
}
I do know that the error is with the table args, but I don't understand why Golang will not accept the tests. It would be great to have some clarity. See test below and error:
import (
"testing"
)
func TestSum(t *testing.T) {
type args struct {
nums []int
}
tests := []struct {
name string
args args
want int
}{
{"test", []int{3, 4}, 7},
{"test", []int{3, 3}, 6},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Sum(tt.args.nums); got != tt.want {
t.Errorf("Sum() = %v, want %v", got, tt.want)
}
})
}
}
cannot use []int literal (type []int) as type args in field value
Upvotes: 1
Views: 4354
Reputation: 255105
It's because the second field of your anonymous structure is args
, not []nums
You should initialize it as with an explicitly typed args
value.
{"test", args{nums: []int{3, 4}}, 7},
Or, if you prefer the field-less struct literals:
{"test", args{[]int{3, 4}}, 7},
Upvotes: 5