안녕하세요 fernvale_54,
mossglen_55가 이미 말했듯, 대응하는 데이터가 없을 수도 있음을 나타내려면 값을 포인터로 표현할 수 있습니다
type Entry struct {
Text *string `json:"bar"`
}
null일 수 있는 값을 실제로 존재하는 값처럼 쓰기 전에 반드시 null인지 검사하세요. 그러지 않으면 panic: runtime error: invalid memory address or nil pointer dereference가 나옵니다. 대략 이런 식으로 하면 됩니다:
var entry Entry
//...unmarsal into Entry
if entry.Text != nil {
// len() is safe in this branch
fmt.Println(len(*entry.Text))
}
JSON 출력을 정리하려면 omitempty와 omitzero 태그도 살펴보세요 (omitzero는 go 1.24에서 추가되어 꽤 최근 기능이라 아직 자료가 많지 않을 수 있습니다)
영어에서 번역·원문 보기Hi fernvale_54,
As mossglen_55 already pointed out, you can represent a value with a pointer to indicate that the corresponding data might be absent
type Entry struct {
Text *string `json:"bar"`
}
When using a value which could possibly be null, remember to check for null before treating that value as one that actually exists, or you'll hit panic: runtime error: invalid memory address or nil pointer dereference, something along these lines works:
var entry Entry
//...unmarsal into Entry
if entry.Text != nil {
// len() is safe in this branch
fmt.Println(len(*entry.Text))
}
For tidier JSON output, also investigate the omitempty and omitzero tags (omitzero arrived with go 1.24 and is fairly recent, so information about it might still be sparse)