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
}
The only way you could determine if a struct was initialized would be to check each element within it to see if it matched what you considered an initialized value for that element should be.
Go by Example: Structs This person struct type has name and age fields. newPerson constructs a new person struct with the given name. You can safely return a pointer to local variable as a local variable will survive the scope of the function. This syntax creates a new struct.
Checking for an empty struct in Go is straightforward in most cases. All you need to do is compare the struct to its zero value composite literal. This method works for structs where all fields are comparable.
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
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
In addition to Charlie's answer and to (sort of) answer asafel's question, if the property's type isn't string, you can check the default value assign by Go to that particular type like this:
type MyStruct struct {
Str string
Bool bool
Int int
Uint uint
}
func main() {
s := MyStruct{}
fmt.Println(s.Str)
fmt.Println(s.Bool)
fmt.Println(s.Int)
fmt.Println(s.Uint)
}
Output:
""
false
0
0
And you can check whether the value "is set" in a struct or not
if (s.Bool == false) {
fmt.Println("Bool is either set to false, or wasn't set");
}
Playground
Well as you might have noticed, you can't technically really check whether the property was set or not, but I think this is a worth addition to Charlie's answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With