Skip to content

Instantly share code, notes, and snippets.

@garukun
Created October 28, 2015 01:20
Show Gist options
  • Save garukun/600e1398eaa174b196d1 to your computer and use it in GitHub Desktop.
Save garukun/600e1398eaa174b196d1 to your computer and use it in GitHub Desktop.
Go reflective with JSON Marshaling
package main
import "fmt"
import "reflect"
import "encoding/json"
func main() {
fmt.Println("Hello, playground")
f([]byte(`{"P":123,"Q":"abc"}`), A{})
}
type A struct {
P int `json:""`
Q string `json:""`
}
func f(s []byte, v interface{}) {
vType := reflect.TypeOf(v)
v1 := reflect.New(vType).Interface()
v2 := reflect.New(vType).Interface()
json.Unmarshal(s, v1)
json.Unmarshal(s, v2)
fmt.Println(v1)
fmt.Println(v2)
fmt.Println(v1 == v2)
fmt.Println(reflect.DeepEqual(v1, v2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment