如何检查是否在结构中设置了属性
发布于 2021-02-01 11:17:37
我试图找到如何检查是否设置了结构属性,但找不到任何方法。
我期待这样的事情,但实际上这是行不通的:
type MyStruct struct {
property string
}
test := new(MyStruct)
if test.property {
//do something with this
}
关注者
0
被浏览
86
1 个回答
-
就像dyoo所说的,
nil
如果您的struct属性是指针,则可以使用。如果您想将它们保留为字符串,可以与进行比较""
。这是一个示例:package main import "fmt" type MyStruct struct { Property string } func main() { s1 := MyStruct{ Property: "hey", } s2 := MyStruct{} if s1.Property != "" { fmt.Println("s1.Property has been set") } if s2.Property == "" { fmt.Println("s2.Property has not been set") } }