A generic solution

With Go generics, a truly elegant solution to the above problem is finally possible — a single function that can return the address of a value of any type, ex. (Go playground):

  1. // Ptr returns *value.
  2. func Ptr[T any](value T) *T {
  3. return &value
  4. }
  5. func main() {
  6. // No local variables and the typed helper functions can be collapsed into
  7. // a single, generic function for getting a pointer to a value.
  8. print(request{
  9. host: Ptr("local"),
  10. port: Ptr(80),
  11. })
  12. }

The function Ptr[T any](T) *T:

  • Takes any value of any type
  • Does not box the value
  • Returns a pointer for that value

How does this all work? What exactly is T? What is any? Keep reading to find out :smiley:…


Next: Getting started