reflect.Value lets a program inspect a value without knowing its concrete type at compile time.

value `reflect.ValueOf` can read facts about a value. Convert through typed accessors only after checking the kind.

Value Inspection

count
value_inspection.go
Replay: real traced execution (multi-file project)
package main

import (
	"fmt"
	"reflect"
)

func main() {
	var count = 7
	value := reflect.ValueOf(count)
	kind := value.Kind()
	asInt := value.Int()
	isEven := asInt%2 == 0

	fmt.Println("count=", count)
	fmt.Println("kind=", kind.String())
	fmt.Println("as_int=", asInt)
	fmt.Println("is_even=", isEven)
}
package main

import (
	"fmt"
	"reflect"
)

func main() {
	var count = 2
	value := reflect.ValueOf(count)
	kind := value.Kind()
	asInt := value.Int()
	isEven := asInt%2 == 0

	fmt.Println("count=", count)
	fmt.Println("kind=", kind.String())
	fmt.Println("as_int=", asInt)
	fmt.Println("is_even=", isEven)
}
package main

import (
	"fmt"
	"reflect"
)

func main() {
	var count = 12
	value := reflect.ValueOf(count)
	kind := value.Kind()
	asInt := value.Int()
	isEven := asInt%2 == 0

	fmt.Println("count=", count)
	fmt.Println("kind=", kind.String())
	fmt.Println("as_int=", asInt)
	fmt.Println("is_even=", isEven)
}
  1. count ← 7, value ← 7, kind ← 0x2, asInt ← 7, isEven ← false

    8func main() {9  var count→ 7 = 7 //@count=2, 1210  value→ 7 := reflect.ValueOf(count7)11  kind→ 0x2 := value7.Kind()12  asInt→ 7 := value7.Int()13  isEven→ false := asInt7%2 == 01415  fmt.Println("count=", count7)16  fmt.Println("kind=", kind0x2.String())17  fmt.Println("as_int=", asInt7)18  fmt.Println("is_even=", isEvenfalse)19}
    outputcount= 7
    kind= int
    as_int= 7
    is_even= false
  1. count ← 2, value ← 2, kind ← 0x2, asInt ← 2, isEven ← true

    8func main() {9  var count→ 2 = 210  value→ 2 := reflect.ValueOf(count2)11  kind→ 0x2 := value2.Kind()12  asInt→ 2 := value2.Int()13  isEven→ true := asInt2%2 == 01415  fmt.Println("count=", count2)16  fmt.Println("kind=", kind0x2.String())17  fmt.Println("as_int=", asInt2)18  fmt.Println("is_even=", isEventrue)19}
    outputcount= 2
    kind= int
    as_int= 2
    is_even= true
  1. count ← 12, value ← 12, kind ← 0x2, asInt ← 12, isEven ← true

    8func main() {9  var count→ 12 = 1210  value→ 12 := reflect.ValueOf(count12)11  kind→ 0x2 := value12.Kind()12  asInt→ 12 := value12.Int()13  isEven→ true := asInt12%2 == 01415  fmt.Println("count=", count12)16  fmt.Println("kind=", kind0x2.String())17  fmt.Println("as_int=", asInt12)18  fmt.Println("is_even=", isEventrue)19}
    outputcount= 12
    kind= int
    as_int= 12
    is_even= true