How to check if a property is set in a structure

I am trying to find how to check if a structure property is set, but I cannot find any way.

I expect something like this, but from this does not work:

type MyStruct struct { property string } test := new(MyStruct) if test.property { //do something with this } 
+8
go
source share
3 answers

As with dyoo, you can use nil if your structure properties are pointers. If you want to save them as strings, you can compare them with "" . Here is an example:

 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

+5
source share

You can use pointers and their nil value to determine if something has been set or not. For example, if you change the structure to

 type MyStruct struct { property *string } 

then property can point to a string value, in which case it was set, or it can be nil , in which case it has not yet been set. This is the approach that protobuf library uses to determine if fields are set or not, as you can see at https://code.google.com/p/goprotobuf/source/browse/README#83

+2
source share

Another way to do this is to set the value to private and use the get / set method. bool can determine if they are installed or not.

 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 } 
-5
source share

All Articles