I'm building a graphql API using 99designs/gqlgen but I'm a bit confused about the proper way of returning pointers.
The graphql type
type GraphType {
image_url: String
}
The go code is:
type GraphType struct {
ImageURL *string `json:"image"`
}
type T struct {
value string
}
func (t T) toImageUrl() string {
return fmt.Sprintf("http://test.localhost/%s", t.value)
}
func (t T) toGraphType() *GraphType {
var items = &GraphType{
}
return items
}
There a 3 ways that I can do this
// toImageUrl returns a pointer
func (t T) toImageUrl() *string {
image := fmt.Sprintf("http://test.localhost/%s", t.value)
return &image
}
var items = &GraphType{
ImageURL: t.toImageUrl(),
}
// store the value and get a pointer
image := t.toImageUrl()
var items = &GraphType{
ImageURL: &image,
}
// make a utility function for poiters
func getPointerString(s string) *string {
return &s
}
var items = &GraphType{
ImageURL: getPointerString(t.toImageUrl()),
}
The easyest is to use getPointerString but I don't know what happens to the momory usages, is this memory safe?