[Golang] json.Unmarshal() Parameter로 nil Pointer를 넘긴다면?

Divan·2023년 9월 6일

json.Unmarshal의 예제를 찾아보면 대부분 Zero구조체를 넘긴다. 하지만 여기에 nil Pointer를 넣어도 제대로 작동하는지 이것이 더욱 효율적인지를 확인

zero struct vs nil pointer

zero struct

type TestType struct {
	LowerCase string `json:"test"`
	UpperCase string `json:"TEST"`
}

func TestUnmarshal(t *testing.T) {
	marshaledByte := []byte("{\"test\": \"test\", \"TEST\": \"TEST\"}")

	testType := &TestType{}
	err := json.Unmarshal(marshaledByte, testType)
	if err != nil {
		t.Error(err)
	}
	
	t.Log("TestType ", testType)
	// Output: &{test TEST}
}

nil pointer

type TestType struct {
	LowerCase string `json:"test"`
	UpperCase string `json:"TEST"`
}

func TestUnmarshal(t *testing.T) {
	marshaledByte := []byte("{\"test\": \"test\", \"TEST\": \"TEST\"}")

	var testType *testType
	err := json.Unmarshal(marshaledByte, &testType)
	if err != nil {
		t.Error(err)
	}
	
	t.Log("TestType ", testType)
	// Output: &{test TEST}
}

결론

nil pointer가 아닌 구조체를 생성해서 Address를 넘기는것이 더 효율적이다. json.umarshal() 내부에서 nil pointer를 확인(reflect 사용)하고, 해당 구조체를 생성하여 그곳에 값을 담아서 준다. 구조체를 생성해서 넘기면 reflect로 type를 확인하는 절차가 생략 됨으로 구조체를 생성해서 넘기는것이 좀 더 효율적이다.

if v.IsNil() {
	v.Set(reflect.New(v.Type().Elem()))
}
profile
하루 25분의 투자

0개의 댓글