Skip to content

Instantly share code, notes, and snippets.

@anolivetree
Created February 26, 2013 22:11
Show Gist options
  • Save anolivetree/5042757 to your computer and use it in GitHub Desktop.
Save anolivetree/5042757 to your computer and use it in GitHub Desktop.
Get/set an field value of a struct
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