如何检查一个空的结构? [英] How to check for an empty struct?

查看:125
本文介绍了如何检查一个空的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个struct ...

 类型Session结构{
playerId string
beehive string
timestamp time.Time
}

有时我会为它分配一个空会话(因为nil是不可能的)

  session = Session {}; 

然后我想检查它是否为空:

  if session == Session {} {
// do stuff ...
}

显然这不起作用。如何编写它?

解决方案

您可以使用==与零值复合文本进行比较,因为所有字段都是可比

  if Session {})==会话{
fmt.Println(是零值)
}

游乐场示例

由于解析歧义,if条件中的复合字面值需要括号。



比较整个值的替代方法是比较必须在有效会话中设置为非零值的字段。例如,如果在有效会话中玩家ID必须是!=,请使用

  if session.playerId == {
fmt.Println(为零值)
}


I define a struct ...

type Session struct {
    playerId string
    beehive string
    timestamp time.Time
}

Sometimes I assign an empty session to it (because nil is not possible)

session = Session{};

Then I want to check, if it is empty:

if session == Session{} {
     // do stuff...
}

Obviously this is not working. How do I write it?

解决方案

You can use == to compare with a zero value composite literal because all fields are comparable:

if (Session{}) == session  {
    fmt.Println("is zero value")
}

playground example

Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.

An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use

if session.playerId == "" {
    fmt.Println("is zero value")
}

这篇关于如何检查一个空的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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