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

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

问题描述

我定义了一个结构......

I define a struct ...

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

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

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")
}

游乐场示例

由于 解析歧义,if 条件中的复合文字需要括号.

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

上述 == 的使用适用于所有字段都可比.如果结构体包含不可比较的字段(切片、映射或函数),则必须将这些字段与它们的零值一一比较.

The use of == above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.

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

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天全站免登陆