Created
December 12, 2017 18:02
-
-
Save jonbodner/b82308022f0f332aa4aa2d1fa7ec39f0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Foo struct { | |
A int `tag1:"First Tag" tag2:"Second Tag"` | |
B string | |
} | |
func main() { | |
greeting := "hello" | |
f := Foo{A: 10, B: "Salutations"} | |
gVal := reflect.ValueOf(greeting) | |
// not a pointer so all we can do is read it | |
fmt.Println(gVal.Interface()) | |
gpVal := reflect.ValueOf(&greeting) | |
// it’s a pointer, so we can change it, and it changes the underlying variable | |
gpVal.Elem().SetString("goodbye") | |
fmt.Println(greeting) | |
fType := reflect.TypeOf(f) | |
fVal := reflect.New(fType) | |
fVal.Elem().Field(0).SetInt(20) | |
fVal.Elem().Field(1).SetString("Greetings") | |
f2 := fVal.Elem().Interface().(Foo) | |
fmt.Printf("%+v, %d, %s\n", f2, f2.A, f2.B) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment