go有没有类似php isset函数

1. 运行环境

当前使用的Go版本1.18

2. 问题描述?

客户端传过来的json,我通过struct进行解析,但是存在几个问题,如果struct下面包含slice下面在包含个slice,我如何判断最里层的某个值是否存在
例子

type Data struct {
    Imp []struct {
        Id      string `json:"id"`
        Slotid  string `json:"slotid"`
        Bid []struct {
            Bidtype  int     `json:"bidtype"`
            Bidfloor float64 `json:"bidfloor"`
        } `json:"bidinfo"`
        Native map[string]interface{} `json:"native"`
    } `json:"imp"`
}

这时候我怎么判断data.imp[0].bid[0].bidfloor是否存在,存在的情况有imp可能是nil或者bid是nil

目前我的做法是len(data.imp) >0 and len(data.imp[0].bidi) >0 然后在进行处理,但是总感觉不是很友好

讨论数量: 11
giao哥

其实用了 go 就不要想着给php一样了。

1年前 评论

你可以自己封装的,你找一个配置包代码看看,例如 config("a.b.c"),大概是把要查的数据转成通用的map、[]interface{}, 循环key一层层判断

1年前 评论
xiaobaiyihao (楼主) 1年前
AB (作者) 1年前

golang struct 里面字段 已经申请内存空间的 所以你直接if 判断值对不对就好了 struct 指针 加一个判断 if 是不是等于nil 就是没有分配内存空间

1年前 评论
xiaobaiyihao (楼主) 1年前
耳东 (作者) 1年前

没有,不要用动态语言的思维来写go

1年前 评论

你把这些分开写在其他struct可以这样吗?

1年前 评论

常用且喜欢的话可以自己封装,比如:

type Data struct {
    Imp []struct {
        Id     string `json:"id"`
        Slotid string `json:"slotid"`
        Bid    []struct {
            Bidtype  int     `json:"bidtype"`
            Bidfloor float64 `json:"bidfloor"`
        } `json:"bidinfo"`
        Native map[string]interface{} `json:"native"`
    } `json:"imp"`
}

func (d Data) IsSet() bool {
    return len (d.Imp) >0 && len (d.Imp[0].Bid) >0
}

func main() {
    d := Data{}
    if d.IsSet() {
        fmt.Println("Bidfloor存在")
    }
}
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!