ProgramGuru

Introduction to Generics

Start with Introduction to Generics

Generics let functions and types work with multiple concrete types while keeping compile-time type checking.

What you’ll learn

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

Understand the idea

Go added type parameters in Go 1.18. A type parameter such as T stands for a type selected at instantiation, and its constraint determines which operations are permitted. any accepts any type, but does not make every operation valid on T.

Use generics when several types genuinely share the same behavior. For simple operations that already have clear concrete types, a non-generic function is often easier to maintain.

Visualize how it works

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

Visual explanation for genericsThe compiler checks each instantiation with its concrete type.Generic template first[T]Step 1Instantiate intStep 2Instantiate stringStep 3Typed outputsStep 4The compiler checks each instantiation with its concrete type.
The compiler checks each instantiation with its concrete type.

Tools, syntax and practical notes

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"

func first[T any](values []T) T { return values[0] }
func main() {
	fmt.Println("First number:", first([]int{8, 9}))
	fmt.Println("First word:", first([]string{"Go", "Rust"}))
}

Output

First number: 8
First word: Go

Trace what the program does

The compiler infers T=int for the first invocation and T=string for the second. The returned values preserve their specific types instead of becoming any values.

Avoid common mistakes

  • The example requires nonempty slices: indexing an empty slice would panic.
  • any does not permit arithmetic on arbitrary T values.

Try it yourself

Write a generic last function and try it with both string and int slices.

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

Check your understanding

What advantage does first[T any] have over returning any?
Choose one answer. You can try again.

Answer and explanation

Its result retains its inferred concrete type

Correct. The compiler infers T=int for the first invocation and T=string for the second.

What you should remember

You have practiced Introduction to Generics 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 Functions →