...

/

Solution Review: Make a Stack with Variable Internal Types

Solution Review: Make a Stack with Variable Internal Types

This lesson discusses the solution to the challenge given in the previous lesson.

We'll cover the following...
package main
import (
	"fmt"
	"mystack"
)

var st1 mystack.Stack

func main() {
	st1.Push("Brown")
	st1.Push(3.14)
	st1.Push(100)
	st1.Push([]string{"Java", "C++", "Python", "C#", "Ruby"})
	for {
		item, err := st1.Pop()
		if err != nil {
			break
		}
		fmt.Println(item)
	}
}

In this program, we develop a generic stack type using a slice holding elements of type interface{ }. This is done in mystack.go in the folder mystack. The stack type is defined at line 4 as: type Stack []interface{}.

This type is an array of items of a generic type interface{}; that means the items can be of any type like ints, strings, booleans, arrays, etc. The following functions are implemented in the file mystack.go:

  • The Len() method amounts to len of the stack array (see line 7 ...