CS 245 - Programming Languages

Lab Nov 14

Slice equality in Go

For most things in Go you can simply ask a==b and get the response you would expect. However, that is not true of slices. Indeed if a and b are slices, then a==b will not even compile. (Maps have similar issues, but we will ignore that for this lab.)

So you need to do more work to determine slice equality. In particular, you need to compare the elements contained in a slice. Usually slices are homogeneous, however they need not be. In particular the main function in the following code shows the creation of a slice with many different data types. Some of which are themselves slices. Note that interface{} in Go is roughly the equivalent of Any in Kotlin or Object in Java.

package main

import (
	"fmt"
	"reflect"
)

func main() {
	var aa = make([]interface{}, 10)
	for i:=0; i<5; i++ {
		aa[i]=i
	}
	aa[5]=int32(32)
	aa[6]="asdf"
	var bb = make([]interface{}, 5)
	for i:=0; i<5; i++ {
		bb[i]=i
	}
	aa[7]=bb
	for i:=8; i<10; i++ {
		aa[i]=int8('a'+i)
	}
	fmt.Printf("%v\n", aa)
	for _, v := range aa {
		fmt.Printf("%v\n", sliceTest(v))
	}
}

// return true if the thing is a slice
func sliceTest(v interface{}) bool{
	rt := reflect.TypeOf(v)
	return rt.Kind()==reflect.Slice
}

// change the thing passed to a slice
// called a "type assertion" in Go, what this says 
// in that the typing really is []interface{}, so please
// treat it as such.   Can only do assertion on interface{}
// Different from a cast in that this is non-converting
// and can only be applied to interface{}
func sliceAssert(aa interface{}) []interface{} {
	return aa.([]interface{})
}

The task in this lab is to write Go code to test for slice equality. Your code need only deal with slices that directly contain slices (ie no slices inside a structs). It need not deal with maps (so no slices inside maps either). Your code will almost certainly need to be recursive.

I expect you will find extremely useful the two functions below the main

What to hand in

Send your final go program to gtowell245@cs.brynmawr.edu. As usual, spend no more than 80 minutes on this task.