jeudi 30 avril 2015

reflect: How to get the name of a struct field?

type User struct { Name string }

func test(o interface{}) {
    t := reflect.TypeOf(o)
    fmt.Println(t)
}

u := &User{"Bob"}
test(u.Name) // prints "string", but I need "Name"

Is this possible in Go? I want to have as few "magic strings" as possible, so instead of having

UpdateFields("Name", "Password")

I'd much rather use

UpdateFields(user.Name, user.Password)





Aucun commentaire:

Enregistrer un commentaire