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 50 of 60 · Go

Advanced Generics – Type Sets & Constraints

Duration: 25 minutes

Type Sets (Go 1.18+)

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

A type set enumerates allowed types for a type parameter.

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

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

Interface constraints with methods

type Stringer interface { String() string }

func Join[T Stringer](elems []T, sep string) string {
    var sb strings.Builder
    for i, e := range elems {
        if i > 0 { sb.WriteString(sep) }
        sb.WriteString(e.String())
    }
    return sb.String()
}

Using generic structs with methods

type Stack[T any] struct { items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
    if len(s.items) == 0 { var zero T; return zero, false }
    idx := len(s.items) - 1
    v := s.items[idx]
    s.items = s.items[:idx]
    return v, true
}

Info

Generics make libraries like maps (golang.org/x/exp/maps) possible without reflection.

Previous: Security Best Practices – Input Validation & SecretsNext: Building a Simple Chat Server (WebSockets + Rooms)