Search⌘ K

Solution Review: Make a Stack with Variable Internal Types

Explore how to develop a generic stack in Go that supports variable internal types using the empty interface. Learn to implement key stack methods such as Push, Pop, and Top with error handling, enabling you to manage collections of mixed data types effectively.

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 ...