ProgramGuru

Generic Types

Start with Generic Types

A generic type stores values of a type parameter while allowing reuse of the same data structure for different element types.

What you’ll learn

  • Explain the main purpose of generic types.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Declare a type such as type Box[T any] struct { Value T }. Box[int] and Box[string] are different instantiated types and retain type checking for their Value fields.

A method on a generic type usually mentions the receiver type parameter, such as func (b Box[T]) Get() T. This kind of method has been available since Go 1.18 and is different from a method declaring its own new type parameters (introduced in Go 1.27).

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for generic typesOne declaration can represent several checked concrete types.Box[T] definitionStep 1Box[int]Step 2Box[string]Step 3Typed Get valuesStep 4One declaration can represent several checked concrete types.
One declaration can represent several checked concrete types.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

type Box[T any] struct{ Value T }

func (b Box[T]) Get() T { return b.Value }
func main() {
	number := Box[int]{Value: 23}
	word := Box[string]{Value: "Go"}
	fmt.Println(number.Get())
	fmt.Println(word.Get())
}

Output

23
Go

Trace what the program does

The same generic Box declaration produces an int-containing value and a string-containing value. Get returns the corresponding concrete type without a type assertion.

Avoid common mistakes

  • Box[int] and Box[string] are not interchangeable types.
  • An instantiated generic type still follows ordinary value and pointer semantics.

Try it yourself

Add a Set method using a pointer receiver and test changing a Box[float64].

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does Box[string] specify?
Choose one answer. You can try again.

Answer and explanation

A Box whose T is string

Correct. The same generic Box declaration produces an int-containing value and a string-containing value.

What you should remember

You have practiced Generic Types in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Generic Structs →