Search code examples
gostructreflect

How to set the composite field of a struct field by name in Go?


I have a struct with one of it's fields being another struct and I would like to access this struct by name (as a parameter). I followed Using reflect, how do you set the value of a struct field? and it works for basic type but not for composite types.

package main

import (
    "fmt"
    "reflect"
)


type PntInt struct {
    p *int64
}

type Foo struct {
    X  int64
    Px PntInt
}

func main() {
    foo := Foo{}
    fmt.Println(foo)
    i := int64(8)
    Pi := PntInt{&i}
    reflect.ValueOf(&foo).Elem().FieldByName("X").SetInt(i)
    reflect.ValueOf(&foo).Elem().FieldByName("Px").Set(Pi)
    fmt.Println(foo)
}

setting the integer works but trying to set "Px" fails with the error

./prog.go:25:52: cannot use Pi (type PntInt) as type reflect.Value in argument to reflect.ValueOf(&foo).Elem().FieldByName("Px").Set

Solution

  • You want to use a Value:

    reflect.ValueOf(&foo).Elem().FieldByName("Px").Set(reflect.ValueOf(Pi))
    

    Here it is running on the Go playground