你好 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)