I'm trying to implement a test in GO. But I'm struggling with the list's syntax inside the struct.
package primeFactor
import "testing"
var testCases = []struct {
p int
expected []int
}{
{15, [3,5]},
{26, [2,13]},
{37, [37]},
{42, [2,3,7]},
}
func TestPrimeFactor(t *testing.T) {
for _, test := range testCases {
observed := PrimeFactor(test.p)
if observed != test.expected {
t.Error("For p = %d, expected %t. Got %t.",
test.p, test.expected, observed)
}
}
}
The output error I have is:
expected ']', found ','
: expected operand, found '{'
: expected ';', found 'for'
I appreciate your help. Thanks.
Toni's answer addresses your specific problem but to address the other issue of comparing slices you'll want to use reflect.DeepEqual
Check out this example:
package main
import (
"fmt"
"reflect"
)
func main() {
observed := []int{1, 2}
expected := []int{1, 3}
if reflect.DeepEqual(observed, expected) {
fmt.Println("Slices are the same")
} else {
fmt.Println("Slices are different")
}
}
Why do you wrote that in the first place? That's not Go syntax. From the spec:
A slice literal describes the entire underlying array literal. Thus, the length and capacity of a slice literal are the maximum element index plus one. A slice literal has the form
[]T{x1, x2, … xn}
So, in your case:
var testCases = []struct {
p int
expected []int
}{
{15, []int{3, 5}},
{26, []int{2, 13}},
{37, []int{37}},
{42, []int{2, 3, 7}},
}
The spec is pretty readable and less scary than one might think. You may want to give it a full look and keep it close for reference.
...and for completeness, here's just a simple example of writing your own function that your test can call to compare the slices:
func slicesMatch(a, b []int) bool {
la := len(a)
lb := len(b)
if la != lb {
return false
}
for i := 0; i < la; i++ {
if a[i] != b[i] {
return false
}
}
return true
}