Skip to content

Instantly share code, notes, and snippets.

@harlow
Created August 4, 2014 04:31
Show Gist options
  • Save harlow/d9af9f12026a15c2cf12 to your computer and use it in GitHub Desktop.
Save harlow/d9af9f12026a15c2cf12 to your computer and use it in GitHub Desktop.
Get and set values of a Struct using reflection in Go Lang
type MyStruct struct {
N int
}
n := MyStruct{ 1 }
// get
immutable := reflect.ValueOf(n)
val := immutable.FieldByName("N").Int()
fmt.Printf("N=%d\n", val) // prints 1
// set
mutable := reflect.ValueOf(&n).Elem()
mutable.FieldByName("N").SetInt(7)
fmt.Printf("N=%d\n", n.N) // prints 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment