I’ve been working on a project using Go Swagger. It can generate your models as golang structs for you. However, if you have a lot of nullable fields, you will end up with structs with a lot of pointer attributes.
If want to conviniently initialize that struct with zero pointers of all the pointer fields, simply use the new(..) keyword instead of declaring variables and then assigining their references to the pointers
package main
import (
"fmt"
)
type Whoa struct {
What *string
Where *string
HowMany *int64
}
func NewWhoa() Whoa {
return Whoa{
What: new(string),
Where: new(string),
HowMany: new(int64),
}
}
func main() {
w := NewWhoa()
fmt.Printf("What [Value=%s Addr=%p]\n", *w.What, w.What)
fmt.Printf("Where [Value=%s Addr=%p]\n", *w.Where, w.Where)
fmt.Printf("HowMany[Value=%d Addr=%p]\n", *w.HowMany, w.HowMany)
}
Output
What [Value= Addr=0x1040c128]
Where [Value= Addr=0x1040c130]
HowMany[Value=0 Addr=0x10414020]