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
}
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")
}
}
You can use pointers and their nil
value to determine whether something has been set or not. For example, if you change your structure to
type MyStruct struct {
property *string
}
then property
can either be pointing to a string value, in which case it was set, or it can be nil
, in which case it hasn't been set yet. This is an approach that the protobuf library uses to determine whether fields are set or not, as you can see in https://code.google.com/p/goprotobuf/source/browse/README#83
Another way to do it would be to make the value private and use a get/set method on it. a bool can determine if set 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
}