Golang Generic for Value to Pointer Function

insomnius logo 2Muhammad Arief Rahman

December 22, 2023

2 min read

Feature WIP


golang logo

Generic type in golang is a way of writing code that allows for the same type of code to be reused without having to write out the same code multiple times. This is done by creating a single function or type that can be used for multiple types of data that are similar in nature. It can be used to simplify code and increase code readability.

One of the use case which I recently found useful is to convert a value into pointer, before generic comes I usually write this kind of function repetitively per type for example:

func StringToPointer(s string) *string {
 return &s
}

func IntToPointer(i int) *int {
 return &i
}

func FloatToPointer(f float64) *float64 {
 return &f
}

func SomeStructToPointer(s SomeStruct) *SomeStruct {
 return &s
}

func PointerToString(s *string) string {
 if s == nil {
  return ""
 }

 return *s
}

func PointerToInt(i *int) int {
 if i == nil {
  return 0
 }

 return *i
}

func PointerToFloat(f *float64) float64 {
 if f == nil {
  return 0
 }
 return *f
}

func PointerToSomeStruct(s *SomeStruct) SomeStruct {
 if s == nil {
  return SomeStruct{}
 }
 return *s
}

But with generic, I only have to write two functions:

func ValueToPointer[V Value](v V) *V {
 return &v
}

func PointerToValue[V Value](v *V) V {
 if v == nil {
  return *new(V)
 }
 return *v
}

This makes development faster and more efficient, as developers don't have to write and maintain separate code for each type of data. With generics, developers can create code that works for any type of data, allowing for greater flexibility and scalability. Imagine the possibilities of generic types in Golang, and how it can help developers write better code more quickly.

meme: magic gif

NOTES: To use generic you should have atleast golang with version 1.18

For full code example you could visit this gist HERE.

You could also find other example in golang github repository here:

  1. Constraint Example
  2. Maps Example
  3. Slices Example