Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 29 of 60 · Go

Generics – Type Parameters (Go 1.18+)

Duration: 25 minutes

Introducing Generics

This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.

Generics let you write reusable data structures without sacrificing type safety.

// A generic slice‑type that can hold any ordered type
func Index[T comparable](slice []T, value T) int {
    for i, v := range slice {
        if v == value { return i }
    }
    return -1
}

Constraints

type Number interface{ ~int | ~int64 | ~float64 }

func Sum[T Number](vals []T) T {
    var total T
    for _, v := range vals { total += v }
    return total
}

Using generic types in structs

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

func (l *List[T]) Add(v T) { l.items = append(l.items, v) }

Info

Generics are compiled away – no runtime cost vs. interface{} implementations.

Previous: Reflection with the `reflect` PackageNext: Tooling – `go fmt`, `go vet`, `golint`, and `staticcheck`