0

Is there a way to avoid instantiating a variable first and then assigning it to a struct which is expecting some property to be a reference value, like in the example below?

type Example struct {
  Active *bool `json:"age,omitempty"`
}

func main() {
  active := false
  e := Example {
    Active: &active,
  }
}

A simple function like the one below(Ref) would remove the need to first create a variable and then use it in the struct, but I am not sure if I won't eventually shoot myself in the foot in the future because of it.

type Example struct {
  Active *bool `json:"age,omitempty"`
}

func main() {
  e := Example {
    Active: Ref(true),
  }
}

func Ref[T any](val T) *T {
  return &val
}
Enthys
  • 301
  • 3
  • 11
  • 3
    As of now, there is not a simpler way to do it. See [proposal: expression to create pointer to simple types](https://github.com/golang/go/issues/45624). It's OK to use a `Ref` function. This is mentioned in this thread: https://groups.google.com/g/golang-nuts/c/mKJbGRRJm7c/m/38gGtL5dNb0J. – Zeke Lu Aug 02 '23 at 09:15

0 Answers0