CodeBlanks Logo Icon CodeBlanks

The reflect package

Learn the basics of the reflect package.

The reflect package

The reflect package lets you inspect the type and contents of a value at run time. You can ask what an any value really is when its type is unknown at compile time.

var x any = 3.14
fmt.Println(reflect.TypeOf(x))  // float64

Packages such as encoding/json and fmt read struct fields this way.

The cost: speed and type safety

Reflection is powerful but has two costs: it is slower than normal code, and mistakes show up as a panic at run time instead of a compile error. That is why interfaces and generics come first; reflect is used when writing truly generic tools (serializers, ORMs, validators).

Practice Print the type

Declare var x any = 42 and print the result of reflect.TypeOf(x) with fmt.Println.

Starter code

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "reflect"
)

func main() {
    var x any = 42
    fmt.Println(reflect.TypeOf(x))
}

Expected output

int

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the reflect package needed most?

  • To read files
  • When inspecting values whose type is unknown at compile time Correct answer
  • To make loops faster
  • To start goroutines

Explanation: reflect reads the real type and fields of a value passed as any at run time; JSON encoders rely on it.

2 Query the type

Question
var x any = "Go"
fmt.Println(reflect.____(x))
Answer
var x any = "Go"
fmt.Println(reflect.TypeOf(x))

Explanation: reflect.TypeOf returns the type of a value (string).

3 reflect concepts

Term Meaning
reflect.TypeOf Returns the type
reflect.ValueOf Wraps the value
any Can hold any type
panic Happens on misuse of reflect

All lessons in Advanced