如何检查是否在结构中设置了属性 [英] How check if a property was set in a struct
本文介绍了如何检查是否在结构中设置了属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到如何检查是否设置了结构属性,但找不到任何方法.
I am trying to find how check if a structure property was set, but i cannot find any way.
我希望像这样,但实际上这是行不通的:
I expect something like this but of corse this not works:
type MyStruct struct {
property string
}
test := new(MyStruct)
if test.property {
//do something with this
}
推荐答案
就像dyoo所说,如果您的struct属性是指针,则可以使用nil
.如果要将它们保留为字符串,可以与""
进行比较.这是一个示例:
Like dyoo said, you can use nil
if your struct properties are pointers. If you want to keep them as strings you can compare with ""
. Here is a sample:
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")
}
}
http://play.golang.org/p/YStKFuekeZ
这篇关于如何检查是否在结构中设置了属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文