Go 泛型作为json解析对象

如果直接这么写:

var dst T
err := json.Unmarshal(v, dst)

当 T 是指针类型时,则会报空指针异常,需要改成:

dst := new(*T)
err := json.Unmarshal(v, dst)

要用 T 类型值的时候,需要两层解引用:

res := make([]T, 0)
dst := new(*T)
err := json.Unmarshal(v, dst)
res = append(res, **dst)
posted @ 2024-03-06 16:04  xDaniel  阅读(27)  评论(0编辑  收藏  举报