Go: Access private fields using reflection

Using reflection, it's possible to read (but not write) unexported fields of a struct defined in another package.

Example

The List struct in package container/list has an unexported field len:

package list

type List struct {
        root Element
        len  int
}

…

This code reads the value of len using reflection:

package main

import (
        "container/list"
        "fmt"
        "reflect"
)

func main() {
        l := list.New()
        l.PushFront("foo")
        l.PushFront("bar")

        // Get a reflect.Value fv for the unexported field len.
        fv := reflect.ValueOf(l).Elem().FieldByName("len")
        fmt.Println(fv.Int()) // 2

        // Try to set the value of len.
        fv.Set(reflect.ValueOf(666)) // ILLEGAL
}
2
panic: reflect: reflect.Value.Set using value obtained using unexported field

goroutine 1 [running]:
reflect.flag.mustBeAssignable(0x1a2, 0x285a)
        /usr/local/go/src/reflect/value.go:225 +0x280
reflect.Value.Set(0xee2c0, 0x10444254, 0x1a2, 0xee2c0, 0x1280c0, 0x82)
        /usr/local/go/src/reflect/value.go:1345 +0x40
main.main()
        ../main.go:18 +0x280

Comments

Be the first to comment!