Go course

GenericsGeneric Types

Go

Display

Theme

Generics · Test exercise

Generic Types

Type parameters aren't just for functions. Structs (and other types) can be generic too, which is perfect for data structures like queues, stacks, or caches that can hold anything.

type Pasangan[K comparable, V any] struct {
	Kunci K
	Nilai V
}

p := Pasangan[string, int]{Kunci: "level", Nilai: 12}

When you create a value of a generic type, you usually have to spell out its type arguments (Pasangan[string, int]), because there are no function arguments to infer them from.

Methods on generic types

Methods repeat the type parameter on the receiver, without the constraint:

type Antrean[T any] struct {
	items []T
}

func (a *Antrean[T]) Masuk(v T) {
	a.items = append(a.items, v)
}

func (a *Antrean[T]) Keluar() (T, bool) {
	var nol T
	if len(a.items) == 0 {
		return nol, false
	}
	depan := a.items[0]
	a.items = a.items[1:]
	return depan, true
}

Notice the var nol T pattern for getting the zero value of any type. It comes in handy when there's no value to return.

Methods can't have extra type parameters of their own. func (a *Antrean[T]) Petakan[U any]() isn't valid; use a regular function for cases like that.

The zero value Antrean[int]{} works right away, because you can append to a nil slice.

Task

A text editor needs an undo feature, and an RPG needs a deck of cards. Both can use a stack (last in, first out). Complete Stack[T any]:

  • func (s *Stack[T]) Push(v T) puts v on top.
  • func (s *Stack[T]) Pop() (T, bool) takes and removes the top element; if the stack is empty, return the zero value and false.
  • func (s *Stack[T]) Intip() (T, bool) looks at the top element without removing it; if the stack is empty, return the zero value and false.
  • func (s *Stack[T]) Len() int returns the number of elements.

The zero value Stack[T]{} must work right away.

main.go
package main

import "fmt"

type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(v T) {
	// TODO
}

func (s *Stack[T]) Pop() (T, bool) {
	// TODO
	var nol T
	return nol, false
}

func (s *Stack[T]) Intip() (T, bool) {
	// TODO
	var nol T
	return nol, false
}

func (s *Stack[T]) Len() int {
	// TODO
	return 0
}

func main() {
	var riwayat Stack[string]
	riwayat.Push("ketik: Halo")
	riwayat.Push("ketik: dunia")
	riwayat.Push("tebalkan: dunia")

	for riwayat.Len() > 0 {
		aksi, _ := riwayat.Pop()
		fmt.Println("Undo:", aksi)
	}
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)