CS 245 - Programming Languages
Lab 4
Sorting Go Slices
In this lab you will create and fill a slice containing instances of a struct. Then you will use the sort function
in Go to set up sorthing on two distinct fields in the struct.
Setup
- Create a struct with 3 fields, an int a float and a string
- Create a slice that holds instances of the struct you created.
- Put into the slice about 10 instances of your struct; each instance should have values of the fields
that are distinct from any other instance. Also, the values in each field should not be in a sorted
order.
- Print the contents of your slice.
Sorting
Go has a concept of interfaces; they are differently implemented than in Java. Basically you do not have to
declare that something implements an interface. Rather, at compile time the program is checked for uns of
functions that require implementing an interface., If the required interface is implemented (usually as
methods on a type), then the compile succeeds and the program runs.
Sorting requires implementing 3 methods on a type
func (p S) Len() int { }
func (p S) Swap(i, j int) { }
func (p S) Less(i, j int) bool { }
Importantly the type that these methods are implemented on needs to be one that hold a slice. So, for
instance,
type IntSlice []int
the somewhere else in your code you might have
aa := make(IntSlice,0)
Implement the methods and sort your slice instance using the functions in the Go "sort" package. (Do not
write your own sort.)
Veryify that the sort works
Now, suppose you want to sort on some other field of your struct. You could do this by adding some
branching inside the Less method and having a global variable to indicate the branch to use. But that is
really ugly. Worse, it will slow down the sort. Instead, define a new type that is just a renaming of
your
struct/slice type. Then implement the Len, Swap and Less functions on your new type. Finally, cast your
slice
from the original type to your new type and sort that thing.
What to hand in
Send to gtowell245@cs.brynmawr.edu a copy of your go program. The program should include everything
described above and a main function, that, when run, shows that different sorts can be done on the same
slice by only
casting the slice to a different types.