Skip to content
insomnius.

Golang Generic for Value to Pointer Function

insomnius logo 2Muhammad Arief Rahman

December 23, 2023

2 min read


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.

The Problem: Repetitive Type Functions

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
}

The Solution: Generic Functions

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
}

Benefits of Generics

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 complete Go generics example.

Additional Resources

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

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

Knowledge Check

1/5

What is the main purpose of generic types in Golang?

0 claps5 remaining

Share this article