Distinguish kind, addressability and settability
Distinguish kind, addressability and settability
A reflect.Value may describe a copy, an addressable variable, or an inaccessible field. Kind tells you which operations fit the representation; CanAddr tells whether Addr is allowed; CanSet tells whether reflection may replace the value. They are separate checks.
package main
import ( "fmt" "reflect")
func main() { n := 7 v := reflect.ValueOf(n) p := reflect.ValueOf(&n).Elem() fmt.Println(v.CanAddr(), v.CanSet()) fmt.Println(p.CanAddr(), p.CanSet()) p.SetInt(12) fmt.Println(n)}Passing n to ValueOf copies the integer into an interface. Passing &n and calling Elem selects the original variable. SetInt requires both an appropriate signed kind and CanSet. For smaller integer types, check OverflowInt before writing to avoid truncation. An ordinary pointer assignment is clearer whenever the type is known.
Expected output:
false falsetrue true12Addressable does not always mean settable
package main
import ( "fmt" "reflect")
type Item struct { Count int hidden int}
func main() { v := reflect.ValueOf(&Item{}).Elem() f := v.FieldByName("hidden") fmt.Println(f.CanAddr(), f.CanSet(), f.CanInterface()) v.FieldByName("Count").SetInt(3) fmt.Println(v.FieldByName("Count").Int())}An unexported field can be addressable but cannot be set or converted to an interface by ordinary reflection. Respect that boundary; do not use unsafe to evade it. Missing fields yield an invalid Value; check IsValid before operations requiring a valid value.
Expected output:
true false false3Try it locally
Change an addressable int8 to 100 only if it can be set and the new value fits; print whether 200 overflows.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 02: Distinguish kind, addressability and settability
Check the lesson objective before moving on.
Which value can SetInt modify?
Does CanAddr imply CanSet?