Search⌘ K
AI Features

Solution Review: Implement Miner Interface

Explore how to implement the Miner interface in Go by defining functions that determine the minimum element in arrays of different data types. Understand how interfaces allow handling various collections generically, and see examples with integer and string arrays. This lesson prepares you for more advanced reflection techniques.

We'll cover the following...
package min
type Miner interface {
	Len() int
	ElemIx(ix int) interface{}
	Less(i, j int) bool
}

func Min(data Miner) interface{}  {
	min := data.ElemIx(0)
	min_idx := 0
	for i:=1; i < data.Len(); i++ {
		if data.Less(i, min_idx) {
				min = data.ElemIx(i)
				min_idx = i
		}
	}
	return min
}

type IntArray []int
func (p IntArray) Len() int           		  { return len(p) }
func (p IntArray) ElemIx(ix int) interface{}  { return p[ix] }
func (p IntArray) Less(i, j int) bool 		  { return p[i] < p[j] }

type StringArray []string
func (p StringArray) Len() int              	 { return len(p) }
func (p StringArray) ElemIx(ix int) interface{}  { return p[ix] }
func (p StringArray) Less(i, j int) bool    	 { return p[i] < p[j] }

In min.go in folder min, we implement the Min function (from line 8 to line 18). At line 9, we take min to be the first element of the collection. Then in the for loop, we traverse the collection comparing the element at i index with the element at index min_idx. When data.Less(i, min_idx) is ...