Golang Reflection Quiz
35 comprehensive questions on Golang's reflection capabilities, covering reflect.Type & reflect.Value usage, value modification, kind checking, performance considerations, and when to avoid reflection — with 15 code examples demonstrating practical reflection techniques.
Question 1
What is reflection in Go?
import "reflect"
type User struct {
Name string
Age int
}
func main() {
u := User{Name: "Alice", Age: 30}
v := reflect.ValueOf(u)
t := reflect.TypeOf(u)
fmt.Println("Type:", t.Name())
fmt.Println("Kind:", t.Kind())
fmt.Println("Fields:", t.NumField())
}Question 2
How do you get reflect.Type from a value?
var x int = 42
t := reflect.TypeOf(x)
fmt.Println("Type:", t)
fmt.Println("Name:", t.Name())
fmt.Println("Kind:", t.Kind())
// For pointers
var p *int
t2 := reflect.TypeOf(p)
fmt.Println("Pointer type:", t2)
fmt.Println("Elem type:", t2.Elem())Question 3
How do you get reflect.Value from a value?
s := "hello"
v := reflect.ValueOf(s)
fmt.Println("Value:", v)
fmt.Println("Type:", v.Type())
fmt.Println("Kind:", v.Kind())
fmt.Println("String:", v.String())
// For interface{}
var i interface{} = 42
v2 := reflect.ValueOf(i)
fmt.Println("Interface value:", v2.Interface())Question 4
How do you check if a reflect.Value is valid?
var v reflect.Value
fmt.Println("Valid:", v.IsValid()) // false
v = reflect.ValueOf(42)
fmt.Println("Valid:", v.IsValid()) // true
// Zero Value
var zero reflect.Value
fmt.Println("Zero valid:", zero.IsValid()) // falseQuestion 5
How do you get the underlying value from reflect.Value?
i := 42
v := reflect.ValueOf(i)
// Get as interface{}
val := v.Interface()
fmt.Println("Interface:", val)
// Type assert back
original := val.(int)
fmt.Println("Original:", original)
// For strings
s := "hello"
v2 := reflect.ValueOf(s)
str := v2.Interface().(string)
fmt.Println("String:", str)Question 6
How do you check the Kind of a reflect.Type?
var x int
v := reflect.ValueOf(x)
t := v.Type()
fmt.Println("Type:", t)
fmt.Println("Kind:", t.Kind())
// Different kinds
fmt.Println("Int kind:", reflect.TypeOf(42).Kind())
fmt.Println("String kind:", reflect.TypeOf("").Kind())
fmt.Println("Slice kind:", reflect.TypeOf([]int{}).Kind())
fmt.Println("Struct kind:", reflect.TypeOf(struct{}{}).Kind())Question 7
How do you iterate over struct fields using reflection?
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
p := Person{Name: "Alice", Age: 30}
v := reflect.ValueOf(p)
t := reflect.TypeOf(p)
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldType := t.Field(i)
fmt.Printf("Field %d: %s = %v (tag: %s)\n",
i, fieldType.Name, field.Interface(), fieldType.Tag)
}Question 8
How do you modify a value using reflection?
func setValue(v reflect.Value, newVal interface{}) {
if v.CanSet() {
v.Set(reflect.ValueOf(newVal))
} else {
fmt.Println("Cannot set value")
}
}
func main() {
x := 42
v := reflect.ValueOf(&x).Elem() // Get pointer to modify
if v.CanSet() {
v.SetInt(100)
fmt.Println("New value:", x) // 100
}
}Question 9
How do you check if a reflect.Value can be set?
x := 42
v1 := reflect.ValueOf(x)
fmt.Println("Can set direct:", v1.CanSet()) // false
v2 := reflect.ValueOf(&x).Elem()
fmt.Println("Can set pointer elem:", v2.CanSet()) // true
// Struct field
s := struct{ A int }{42}
v3 := reflect.ValueOf(&s).Elem().Field(0)
fmt.Println("Can set struct field:", v3.CanSet()) // trueQuestion 10
How do you call a function using reflection?
func add(a, b int) int {
return a + b
}
func main() {
fn := reflect.ValueOf(add)
args := []reflect.Value{
reflect.ValueOf(10),
reflect.ValueOf(20),
}
result := fn.Call(args)
fmt.Println("Result:", result[0].Interface()) // 30
}Question 11
How do you create a new value using reflection?
t := reflect.TypeOf(42)
// Create zero value
v1 := reflect.New(t)
fmt.Println("Zero value:", v1.Interface()) // *int pointing to 0
// Create slice
t2 := reflect.TypeOf([]int{})
v2 := reflect.MakeSlice(t2, 0, 10)
fmt.Println("Slice:", v2.Interface()) // []
// Create map
t3 := reflect.TypeOf(map[string]int{})
v3 := reflect.MakeMap(t3)
fmt.Println("Map:", v3.Interface()) // map[]Question 12
How do you handle struct tags with reflection?
type Config struct {
Host string `json:"host" validate:"required"`
Port int `json:"port" validate:"min=1,max=65535"`
Timeout time.Duration `json:"timeout"`
}
c := Config{}
t := reflect.TypeOf(c)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
jsonTag := field.Tag.Get("json")
validateTag := field.Tag.Get("validate")
fmt.Printf("Field: %s, JSON: %s, Validate: %s\n",
field.Name, jsonTag, validateTag)
}Question 13
How do you check if a type implements an interface?
type Writer interface {
Write([]byte) (int, error)
}
type MyWriter struct{}
func (w *MyWriter) Write(data []byte) (int, error) {
return len(data), nil
}
func main() {
t := reflect.TypeOf((*MyWriter)(nil))
writerType := reflect.TypeOf((*Writer)(nil)).Elem()
fmt.Println("Implements Writer:", t.Implements(writerType))
// Or check method
method, ok := t.MethodByName("Write")
fmt.Println("Has Write method:", ok)
}Question 14
How do you get method information using reflection?
type Calculator struct{}
func (c Calculator) Add(a, b int) int {
return a + b
}
func main() {
t := reflect.TypeOf(Calculator{})
method, ok := t.MethodByName("Add")
if ok {
fmt.Println("Method:", method.Name)
fmt.Println("Type:", method.Type)
fmt.Println("Inputs:", method.Type.NumIn())
fmt.Println("Outputs:", method.Type.NumOut())
}
// All methods
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
fmt.Println("Method", i, ":", m.Name)
}
}Question 15
How do you handle slice reflection operations?
s := []int{1, 2, 3}
v := reflect.ValueOf(s)
fmt.Println("Len:", v.Len())
fmt.Println("Cap:", v.Cap())
// Get element
fmt.Println("Element 0:", v.Index(0).Interface())
// Append
newSlice := reflect.Append(v, reflect.ValueOf(4))
fmt.Println("Appended:", newSlice.Interface())
// Set element (if addressable)
s2 := []int{1, 2, 3}
v2 := reflect.ValueOf(&s2).Elem()
v2.Index(0).SetInt(99)
fmt.Println("Modified:", s2)Question 16
How do you handle map reflection operations?
m := map[string]int{"a": 1, "b": 2}
v := reflect.ValueOf(m)
// Get keys
keys := v.MapKeys()
for _, key := range keys {
value := v.MapIndex(key)
fmt.Printf("%s: %v\n", key.Interface(), value.Interface())
}
// Set value
m2 := map[string]int{}
v2 := reflect.ValueOf(&m2).Elem()
key := reflect.ValueOf("newkey")
val := reflect.ValueOf(42)
v2.SetMapIndex(key, val)
fmt.Println("Map:", m2)Question 17
What are the performance implications of reflection?
Question 18
How do you implement a generic function using reflection?
func printTypeAndValue(x interface{}) {
t := reflect.TypeOf(x)
v := reflect.ValueOf(x)
fmt.Printf("Type: %s, Value: %v\n", t, v.Interface())
}
func main() {
printTypeAndValue(42)
printTypeAndValue("hello")
printTypeAndValue([]int{1, 2, 3})
}Question 19
How do you handle pointer types with reflection?
x := 42
p := &x
v := reflect.ValueOf(p)
fmt.Println("Type:", v.Type()) // *int
fmt.Println("Kind:", v.Kind()) // ptr
// Dereference
elem := v.Elem()
fmt.Println("Elem type:", elem.Type()) // int
fmt.Println("Elem value:", elem.Interface()) // 42
// Modify through pointer
if elem.CanSet() {
elem.SetInt(100)
fmt.Println("Modified x:", x) // 100
}Question 20
How do you implement deep equality using reflection?
func deepEqual(a, b interface{}) bool {
va := reflect.ValueOf(a)
vb := reflect.ValueOf(b)
return reflect.DeepEqual(va.Interface(), vb.Interface())
}
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
fmt.Println("Equal:", deepEqual(a, b)) // true
// Or use reflect.DeepEqual directly
fmt.Println("Direct:", reflect.DeepEqual(a, b)) // true
}Question 21
How do you check if a field is exported using reflection?
type Person struct {
Name string // exported
age int // unexported
}
p := Person{Name: "Alice", age: 30}
t := reflect.TypeOf(p)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
fmt.Printf("Field %s: Exported = %t\n",
field.Name, field.PkgPath == "")
}Question 22
How do you implement a simple JSON marshaler using reflection?
func simpleMarshal(v interface{}) ([]byte, error) {
val := reflect.ValueOf(v)
typ := reflect.TypeOf(v)
if typ.Kind() != reflect.Struct {
return nil, fmt.Errorf("only structs supported")
}
result := make(map[string]interface{})
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
if fieldType.PkgPath != "" {
continue // skip unexported
}
tag := fieldType.Tag.Get("json")
name := fieldType.Name
if tag != "" {
name = tag
}
result[name] = field.Interface()
}
return json.Marshal(result)
}Question 23
How do you handle channel types with reflection?
ch := make(chan int, 5)
v := reflect.ValueOf(ch)
t := v.Type()
fmt.Println("Type:", t) // chan int
fmt.Println("Kind:", t.Kind()) // chan
fmt.Println("Elem type:", t.Elem()) // int
// Send
v.Send(reflect.ValueOf(42))
// Receive
result, ok := v.Recv()
fmt.Println("Received:", result.Interface(), "ok:", ok)
// Close
v.Close()Question 24
How do you implement a type switch using reflection?
func typeSwitch(v interface{}) string {
switch reflect.TypeOf(v).Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return "integer"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "unsigned integer"
case reflect.Float32, reflect.Float64:
return "float"
case reflect.String:
return "string"
case reflect.Bool:
return "boolean"
case reflect.Slice:
return "slice"
case reflect.Map:
return "map"
default:
return "other"
}
}
func main() {
fmt.Println(typeSwitch(42)) // integer
fmt.Println(typeSwitch("hello")) // string
fmt.Println(typeSwitch([]int{})) // slice
}Question 25
How do you handle interface{} values with reflection?
func processInterface(v interface{}) {
val := reflect.ValueOf(v)
if val.Kind() == reflect.Interface {
// Unwrap interface
elem := val.Elem()
fmt.Println("Interface contains:", elem.Type())
if elem.IsValid() {
processValue(elem)
}
} else {
processValue(val)
}
}
func processValue(v reflect.Value) {
fmt.Printf("Type: %s, Value: %v\n", v.Type(), v.Interface())
}Question 26
What are the main performance costs of reflection?
Question 27
How do you implement a simple ORM using reflection?
type Model struct {
ID int `db:"id"`
Name string `db:"name"`
}
func (m *Model) Save() error {
t := reflect.TypeOf(*m)
v := reflect.ValueOf(*m)
fields := make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
tag := field.Tag.Get("db")
if tag == "" {
continue
}
fields[tag] = value.Interface()
}
// Simulate database insert
return insertIntoDB(t.Name(), fields)
}Question 28
How do you handle recursive types with reflection?
type Node struct {
Value int
Left *Node
Right *Node
}
func printTree(n *Node, depth int) {
if n == nil {
return
}
indent := strings.Repeat(" ", depth)
fmt.Printf("%sValue: %d\n", indent, n.Value)
if n.Left != nil {
fmt.Printf("%sLeft:\n", indent)
printTree(n.Left, depth+1)
}
if n.Right != nil {
fmt.Printf("%sRight:\n", indent)
printTree(n.Right, depth+1)
}
}
// Using reflection
func printTreeReflect(v reflect.Value, depth int) {
if !v.IsValid() || v.IsNil() {
return
}
indent := strings.Repeat(" ", depth)
// Get Value field
valueField := v.Elem().FieldByName("Value")
fmt.Printf("%sValue: %v\n", indent, valueField.Interface())
// Recurse on Left and Right
leftField := v.Elem().FieldByName("Left")
if !leftField.IsNil() {
fmt.Printf("%sLeft:\n", indent)
printTreeReflect(leftField, depth+1)
}
rightField := v.Elem().FieldByName("Right")
if !rightField.IsNil() {
fmt.Printf("%sRight:\n", indent)
printTreeReflect(rightField, depth+1)
}
}Question 29
How do you implement validation using reflection?
type Validator struct {
Rules map[string][]string
}
func (v *Validator) Validate(s interface{}) []string {
val := reflect.ValueOf(s)
typ := reflect.TypeOf(s)
var errors []string
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
fieldName := fieldType.Name
rules, exists := v.Rules[fieldName]
if !exists {
continue
}
for _, rule := range rules {
if !v.checkRule(field, rule) {
errors = append(errors, fmt.Sprintf("%s failed %s", fieldName, rule))
}
}
}
return errors
}
func (v *Validator) checkRule(field reflect.Value, rule string) bool {
// Implement rule checking logic
return true // placeholder
}Question 30
When should you avoid using reflection?
Question 31
How do you implement method chaining using reflection?
type Builder struct {
value reflect.Value
}
func NewBuilder(x interface{}) *Builder {
return &Builder{value: reflect.ValueOf(&x).Elem()}
}
func (b *Builder) Set(field string, value interface{}) *Builder {
f := b.value.FieldByName(field)
if f.IsValid() && f.CanSet() {
f.Set(reflect.ValueOf(value))
}
return b
}
func (b *Builder) Get() interface{} {
return b.value.Interface()
}
func main() {
type Config struct {
Host string
Port int
}
c := Config{}
result := NewBuilder(&c).
Set("Host", "localhost").
Set("Port", 8080).
Get()
fmt.Printf("%+v\n", result)
}Question 32
How do you handle embedded structs with reflection?
type Base struct {
ID int
}
type Derived struct {
Base
Name string
}
func main() {
d := Derived{Base: Base{ID: 1}, Name: "test"}
v := reflect.ValueOf(d)
t := reflect.TypeOf(d)
// Iterate all fields including embedded
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
value := v.Field(i)
fmt.Printf("Field: %s, Value: %v, Anonymous: %t\n",
field.Name, value.Interface(), field.Anonymous)
}
// Access embedded field directly
baseField := v.FieldByName("Base")
idField := baseField.FieldByName("ID")
fmt.Println("ID:", idField.Interface())
}Question 33
How do you implement a deep copy using reflection?
func deepCopy(src interface{}) interface{} {
srcVal := reflect.ValueOf(src)
srcType := reflect.TypeOf(src)
dstVal := reflect.New(srcType).Elem()
copyValue(dstVal, srcVal)
return dstVal.Interface()
}
func copyValue(dst, src reflect.Value) {
switch src.Kind() {
case reflect.Ptr:
if !src.IsNil() {
dst.Set(reflect.New(src.Type().Elem()))
copyValue(dst.Elem(), src.Elem())
}
case reflect.Struct:
for i := 0; i < src.NumField(); i++ {
copyValue(dst.Field(i), src.Field(i))
}
case reflect.Slice:
if !src.IsNil() {
dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap()))
for i := 0; i < src.Len(); i++ {
copyValue(dst.Index(i), src.Index(i))
}
}
default:
dst.Set(src)
}
}Question 34
How do you implement a plugin system using reflection?
type Plugin interface {
Name() string
Execute(data interface{}) interface{}
}
func loadPlugin(pluginPath string) (Plugin, error) {
// Load .so file (simplified)
// p, err := plugin.Open(pluginPath)
// sym, err := p.Lookup("Plugin")
// return sym.(Plugin), err
return nil, nil // placeholder
}
func executePlugin(p Plugin, data interface{}) interface{} {
// Use reflection to call methods
v := reflect.ValueOf(p)
method := v.MethodByName("Execute")
args := []reflect.Value{reflect.ValueOf(data)}
result := method.Call(args)
return result[0].Interface()
}Question 35
What is the most important principle for using reflection effectively?
