转到:如何检查struct属性是否显式设置为零值? [英] Go: How to check if a struct property was explicitly set to a zero value?

查看:56
本文介绍了转到:如何检查struct属性是否显式设置为零值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type Animal struct {
    Name string
    LegCount int
}

snake := Animal{Name: "snake", LegCount: 0}
worm := Animal{Name: "worm"}

问题:设置后,如何检查 snake worm ,以告知:

Question: How can I check snake and worm after they've been set, to tell that:

  1. snake 已明确设置为 LegCount 为0.
  2. 没有明确设置 worm LegCount (因此基于其默认值)?
  1. snake was explicitly set with a LegCount of 0.
  2. The worm's LegCount was not explicitly set (and therefore based off of its default value)?

推荐答案

根本无法区分.

如果要从XML或JSON解组数据,请使用指针.

If you are unmarshalling data from XML or JSON, use pointers.

type Animal struct {
    Name *string
    LegCount *int
}

对于缺少的字段,您将获得 nil 值.

You will get nil values for absent fields.

在您的情况下,您可以使用相同的约定.

You can use the same convention in your case.

这篇关于转到:如何检查struct属性是否显式设置为零值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆