vendredi 16 janvier 2015

How get pointer of struct's member from interface{} (reflection). Golang

I want to pass struct's pointer to function that expect interface{}. Then get (through reflection) the pointer to the struct's member and then modify it using this pointer. I've read a much of Q&A and tried much of variations, but still I can get it work.


Let's consider example below:



type Robot struct {
Id int
}
f := func(i interface {}) {
v := reflect.ValueOf(i).Elem().FieldByName("Id")
ptr := v.Addr().Pointer()
*ptr = 100
//^ it needs to me for functions expecting the pointer: Scan(&pointerToValue)
}

robot := &Robot{}
f(robot)
println(robot.Id) //I want to get here 100





Aucun commentaire:

Enregistrer un commentaire