1

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?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
siper92
  • 23
  • 4
  • @blackgreen I have no idea that's why I'm asking. Maybe it leaves dangling pointers that leads to memory leeks. But from the explanation of AJR this should be safe – siper92 Oct 21 '22 at 07:58

1 Answers1

1

Unlike other languages you can safely return a pointer to a local variable due to Go's amazing "escape analysis". So yes, using getPointerString is safe.

But I really don't think you need to return NULL. So you don't need a nullable string in your schema. Simply use String! instead of String then you can just return a Go string instead of needing a pointer to the string. Ie:

type GraphType {
  image_url: String!
}
type GraphType struct {
    ImageURL string `json:"image"`
}
AJR
  • 1,547
  • 5
  • 16
  • I kind of need the null value, because I use typescript and react query with autogenerated types the nulability signifies which fields are not required, and for which fields a value my not be presant. The example was very simplified and yes I don't need a nulable value for 1 field. – siper92 Oct 20 '22 at 10:10