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

Reflection with the `reflect` Package

Duration: 20 minutes

Reflection Basics

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

reflect lets you inspect types at runtime – useful for generic libraries.

func Dump(v interface{}) {
    rv := reflect.ValueOf(v)
    rt := rv.Type()
    fmt.Printf("type: %s, kind: %s\n", rt, rt.Kind())
    for i := 0; i < rv.NumField(); i++ {
        f := rt.Field(i)
        val := rv.Field(i).Interface()
        fmt.Printf("%s = %v\n", f.Name, val)
    }
}

Setting values via reflection

func SetField(obj interface{}, name string, value interface{}) error {
    rv := reflect.ValueOf(obj).Elem()
    fv := rv.FieldByName(name)
    if !fv.IsValid() || !fv.CanSet() { return fmt.Errorf("cannot set %s", name) }
    fv.Set(reflect.ValueOf(value))
    return nil
}

Warning

Reflection bypasses compile‑time safety and is slower – use sparingly.

Previous: Graceful Shutdown of ServersNext: Generics – Type Parameters (Go 1.18+)