I pass the structure as an interface I want to fill it with values. field names are known. How can this be done? Found that this is done using the package reflect. I did as in the description of v := reflect.ValueOf(data).Elem() v.FieldByName("UserName").SetString("Greg") expect that after executing these methods in the structure of data in the UserName field will be the string Greg. I get the error panic: reflect: call of reflect.Value.FieldByName on interface Value [recovered] panic: reflect: call of reflect.Value.FieldByName on interface Value

1 answer 1

Show your code. Usually, it works like this:

 type User struct { Name string } func setName(u interface{}) { v := reflect.ValueOf(u) v.Elem().FieldByName("Name").SetString("Greg") } func main() { u := &User{} setName(u) fmt.Println(u) } 

Playground: https://play.golang.org/p/5voMPz27fk .