having a rough time working with struct fields using reflect
package. in particular, have not figured out how to set the field value.
type t struct { fi int; fs string } var r t = t{ 123, "jblow" } var i64 int64 = 456
getting Name of field i - this seems to work
var field = reflect.TypeOf(r).Field(i).Name
getting value of field i as a) interface{}, b) int - this seems to work
var iface interface{} = reflect.ValueOf(r).Field(i).Interface()
var i int = int(reflect.ValueOf(r).Field(i).Int())
setting value of field i - try one - panic
reflect.ValueOf(r).Field(i).SetInt( i64 )
panic: reflect.Value·SetInt using value obtained using unexported field
assuming it did not like field names "id" and "name", so renamed to "Id" and "Name"
a) is this assumption correct?
b) if correct, thought not necessary since in same file / package
setting value of field i - try two (with field names capitalized ) - panic
reflect.ValueOf(r).Field(i).SetInt( 465 )
reflect.ValueOf(r).Field(i).SetInt( i64 )
panic: reflect.Value·SetInt using unaddressable value
Instructions below by @peterSO are thorough and high quality
Four. this works:
reflect.ValueOf(&r).Elem().Field(i).SetInt( i64 )
he documents as well that the field names must be exportable (begin with capital letter)
Go is available as open source code. A good way to learn about reflection is to see how the core Go developers use it. For example, the Go fmt and json packages. The package documentation has links to the source code files under the heading Package files.
The Go json package marshals and unmarshals JSON from and to Go structures.
Here's a step-by-step example which sets the value of a
struct
field while carefully avoiding errors.The Go
reflect
package has aCanAddr
function.The Go
reflect
package has aCanSet
function, which, iftrue
, implies thatCanAddr
is alsotrue
.We need to make sure we can
Set
thestruct
field. For example,If we can be certain that all the error checks are unnecessary, the example simplifies to,
This seems to work:
Prints: