Golang Generic for Value to Pointer Function

insomnius logo 2Muhammad Arief Rahman

December 22, 2023

2 min read

loading...

golang


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

Test Your Knowledge

What is the main purpose of generic types in Golang?

To make code run faster
To allow the same code to be reused for multiple types of data
To reduce memory usage
To make debugging easier

What is one practical use case for generics mentioned in the article?

Database connections
HTTP requests
Converting values to pointers
File handling

What is the minimum Golang version required to use generics?

1.16
1.17
1.18
1.20

How many functions are needed with generics to handle both value-to-pointer and pointer-to-value conversions for any type?

One function
Two functions
Four functions
Eight functions

What happens in the PointerToValue function if the input pointer is nil?

It returns nil
It returns a panic error
It returns a zero value of the type
It returns an empty interface

Share this post