Skip to content

Instantly share code, notes, and snippets.

@jonbodner
Created December 12, 2017 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonbodner/b82308022f0f332aa4aa2d1fa7ec39f0 to your computer and use it in GitHub Desktop.
Save jonbodner/b82308022f0f332aa4aa2d1fa7ec39f0 to your computer and use it in GitHub Desktop.
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