Skip to content
Learn Netverks

Lesson

Step 31/36 86% through track

generics-go

Generics

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
advanced

This lesson

This lesson teaches Generics: the syntax, patterns, and safety habits you need before advancing in Go.

Teams still ship Generics in Go codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Generics in contexts like: Kubernetes ecosystem tools, cloud APIs, and CLI utilities.

Write Go in main.go with package main and func main(), click Run on server—the dev runner runs go run main.go; use fmt.Println for output (requires Go toolchain; LEARNING_RUNNER_ENABLED=true).

When pointers, structs, and basic control flow from intermediate lessons are familiar.

Since Go 1.18, type parameters enable generic functions and types: func Map[T, U any](s []T, f func(T) U) []U. Use when algorithms repeat for many types—avoid premature abstraction.

Constraints

func Sum[T ~int | ~float64](nums []T) T {
    var total T
    for _, n := range nums { total += n }
    return total
}

Constraints live in interfaces—comparable, any, or custom union constraints with |.

Compared to Java/C#

Go generics are reified but simpler than Java wildcards or C# variance—still prefer interfaces when behavior differs, not just types.

Important interview questions and answers

  1. Q: When use generics?
    A: Shared algorithms on slices/maps/channels across types—containers and utilities, not every struct.
  2. Q: any vs interface{}?
    A: any is alias for empty interface—prefer in generic constraints for clarity.

Self-check

  1. What Go version added generics?
  2. What keyword declares type parameters?

Pitfall: Do not genericize everything—prefer plain functions until the same algorithm repeats for many unrelated types.

Interview prep

When use generics?

Shared algorithms across types—containers and utilities, not every struct field.

Go version for generics?

Go 1.18+ with type parameters and constraints.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Type parameter when?
  • comparable constraint?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump