如何检查嵌套结构中的键是否存在

huangapple go评论88阅读模式
英文:

How to check for the existence of key in a nested struct

问题

我有以下的结构体:

type GiphyJson struct {
    Type string `json:"type"`
    Data []struct {
        Images struct {
            Fixed_height struct {
                Url string `json:"url"`
            } `json:"fixed_height"`
        } `json:"images"`
    } `json:"data"`
}

我需要访问 Data[x].Images.Fixed_height.Url。理想情况下,我想在访问 Url 之前检查每个属性(Data、Images、Fixed_height)的存在,以确保我没有空指针异常。由于我对该语言还比较新,我想知道如何以惯用方式实现这一点。

以下是我使用该结构体的方式:

var err error
var giphyJson GiphyJson
keyword = url.QueryEscape(keyword)
resp, err := http.Get("http://api.giphy.com/v1/gifs/search?q=" + keyword + "&api_key=dc6zaTOxFJmzC&limit=100")
if err != nil {
    err = errors.New("An error occured trying to contact giphy")
    return "", err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(bodyBytes, &giphyJson)

请注意,这只是翻译的部分,不包括回答你的问题。

英文:

I have the following struct

   type GiphyJson struct {
    	Type string `json:"type"`
    	Data []struct {
    		Images struct {
    			Fixed_height struct {
    				Url string `json:"url"`
    			} `json:"fixed_height"`
    		} `json:"images"`
    	} `json:"data"`
    }

and I need to access Data[x].Images.Fixed_height.Url. Ideally I'd like to be able to check for the existence of each of the Properties 'Data, Images, ,Fixed_height' before accessing Url to ensure I don't have a nil pointer exceptions. Since I'm fairly new to the language I was curious what the idiomatic way of doing this would be.

The following is how i'm using the struct.

var err error
var giphyJson GiphyJson
keyword = url.QueryEscape(keyword)
resp, err := http.Get("http://api.giphy.com/v1/gifs/search?q=" + keyword + "&api_key=dc6zaTOxFJmzC&limit=100")
if err != nil {
	err = errors.New("An error occured trying to contact giphy")
	return "", err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(bodyBytes, &giphyJson)

答案1

得分: 3

根据该结构的定义,唯一需要检查的是 len(Data) > x。除此之外,所有的值类型都没有发生空引用恐慌的风险。

if len(Data) > x {
    // 访问
    fmt.Println(Data[x].Images.Fixed_height.Url)
} else {
   // 处理其他意外输入的操作
}
英文:

The only required check (based on the definition of that struct) is that len(Data) > x. Beyond that, everything is a value type so there is no risk of a nil reference panic happening.

if len(Data) > x {
    // access
    fmt.Println(Data[x].Images.Fixed_height.Url)
} else {
   // do other stuff you to mitigate unexpected input
}

huangapple
  • 本文由 发表于 2016年11月4日 02:43:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/40409054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定