Created
August 4, 2014 04:31
-
-
Save harlow/d9af9f12026a15c2cf12 to your computer and use it in GitHub Desktop.
Get and set values of a Struct using reflection in Go Lang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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