I would like to know how to set a variable using reflection when using an interface{}
value, and all kind of structs could be passed to func F(o interface{})
. How to change the first value (s.A) to 'hello'?
package main
import (
"fmt"
"reflect"
)
type T struct {
A string
}
func main() {
F(T{"foo"})
}
func F(o interface{}) {
t := reflect.ValueOf(&T{"bar"}).Elem()
s := reflect.ValueOf(&o).Elem()
// ok
fmt.Println("struct: ", t.Field(0).CanSet())
// panics - how to set s.A?
fmt.Println("interface:", s.Field(0).CanSet())
}