In my point of view, reflect.ValueOf(&x).Elem()
is equal to reflect.ValueOf(x)
because .Elem()
is get the real value of the pointer that reflect.Value
contains. Here comes the code, the encoding results by json.Marshal
are different:
func generateRequest(input string, flag bool) interface{} {
val := Node {
Cmd: "Netware",
Name: input,
}
if flag {
return &val
} else {
return val
}
}
func main() {
request1 := generateRequest("123", true)
request2 := generateRequest("123", false)
request1Val := reflect.ValueOf(request1).Elem()
fmt.Println(request1Val, request2)
json1, err := json.Marshal(request1Val)
checkErr(err)
json2, err := json.Marshal(request2)
checkErr(err)
fmt.Println(json1, string(json1))
fmt.Println(json2, string(json2))
fmt.Println(reflect.DeepEqual(json1, json2))
}
And belowing is the output:
{Netware 123} {Netware 123}
[123 34 102 108 97 103 34 58 52 48 57 125] {"flag":409}
[123 34 99 109 100 34 58 34 78 101 116 119 97 114 101 34 44 34 110 97 109 101 34 58 34 49 50 51 34 125] {"cmd":"Netware","name":"123"}
false
I wonder why they are different, and how to modify my code to make the encoding result of request1
same as request2
.