如何检查一个空的结构? [英] How to check for an empty 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")
}
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屋!