如何检查是否在结构中设置了属性

时间:2013-12-12 21:02:17

标签: go

我试图找出如何检查结构属性是否已设置,但我找不到任何方法。

我希望像这样的东西,但是这样不可行:

type MyStruct struct {
    property    string
}

test := new(MyStruct)
if test.property {
    //do something with this
}

3 个答案:

答案 0 :(得分:10)

就像dyoo所说,如果你的struct属性是指针,你可以使用nil。如果您想将它们保留为字符串,则可以与""进行比较。这是一个示例:

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

答案 1 :(得分:4)

您可以使用指针及其nil值来确定是否已设置某些内容。例如,如果将结构更改为

type MyStruct struct {
    property *string
}

然后property可以指向字符串值,在这种情况下它已设置,或者它可以是nil,在这种情况下它尚未设置。这是protobuf库用于确定是否设置字段的方法,如https://code.google.com/p/goprotobuf/source/browse/README#83

中所示。

答案 2 :(得分:-8)

另一种方法是将值设为私有,并对其使用get / set方法。 bool可以确定是否设置。

type MyStruct struct {
    isPropertySet bool
    property string
}

func (my *MyStruct) SetProperty(val string) {
    my.property = val
    my.isPropertySet = true
}

func (my *MyStruct) IsPropertySet() bool {
    return my.isPropertySet
}