Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abhishek-buragadda/a65a6bfc86c0f3c22e031b6571580c1d to your computer and use it in GitHub Desktop.
Save abhishek-buragadda/a65a6bfc86c0f3c22e031b6571580c1d to your computer and use it in GitHub Desktop.
GET/SET a struct field by name in golang
package main
import (
"fmt"
"reflect"
)
type Test struct {
One string
Two string
}
func main() {
test := Test{One: "1", Two: "2"}
fmt.Println("%v", test)
if hasField(test, "Two") {
// you need to pass the reference, inorder to edit the field inside a struct.
setField(&test, "Two", "3")
}
fmt.Println("%v", test)
}
func hasField(v interface{}, name string) bool {
rv := reflect.ValueOf(v)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Struct {
return false
}
return rv.FieldByName(name).IsValid()
}
func setField(v interface{}, name string, value interface{}) {
rv := reflect.ValueOf(v).Elem()
if rv.FieldByName(name).IsValid() {
// comparing kind of field in the struct and the value given the arguement.
if rv.FieldByName(name).Kind() == reflect.ValueOf(value).Kind() {
rv.FieldByName(name).Set(reflect.ValueOf(value))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment