1 of 22

Generics in Golang

1

Mohit Kumar

2 of 22

2

3 of 22

Let’s sort integers

3

4 of 22

Let’s sort floats

4

5 of 22

Let’s sort a custom float64 type

5

6 of 22

How did we solve this prior to Generics?

6

7 of 22

Reflection

7

8 of 22

Let’s talk about it!!

  • Introspect and Analyze program during run-time
  • Interface values
  • The empty interface
  • How do you use it?

8

9 of 22

Reflection

  • Let’s create a SQL INSERT query generator

9

10 of 22

Reflection

  • But it should be a dynamic one

  • Solution
  • sort - Go Packages

10

11 of 22

Then why do we need Generics?

11

12 of 22

Issues with Reflection

12

  • Clear is better than clever. Reflection is never clear.Rob Pike
  • Awkward Programming Model
  • Does not provide compile time check. Dynamic is dangerous
  • Poor Performance

13 of 22

Generics

13

14 of 22

Generics💪

  • Way of writing code that is independent of the specific types being used.
  • Aims to write interoperable and adaptable code.

14

15 of 22

Let’s break it down

15

  1. Type parameters for functions and types
  2. Type sets defined by interfaces
  3. Type Inference

16 of 22

Let’s see a real implementation

16

17 of 22

When to use generics?

17

  1. Write code, don’t design types.
  2. Functions that work on slices, maps, and channels of any element type and the code doesn’t make any assumption of the element type of the above
  3. General purpose data structure
  4. When a method looks the same for all the types

18 of 22

When not to use generics?

18

  1. When just calling a method on the type argument.

19 of 22

When not to use generics?

19

  1. When the implementation of a common method is different for each type.
  2. When the implementation is different for each type and not all the types have to implement the operation

20 of 22

One Thumb Rule

20

Avoid boilerplate

Corollary, don’t use type parameters prematurely; wait until you are about to write boilerplate code

21 of 22

21

Questions?

22 of 22

References

22

  1. https://go.dev/blog/intro-generics
  2. GopherCon 2021: Robert Griesemer & Ian Lance Taylor - Generics!
  3. pkg.go.dev
  4. https://drmarkclewis.medium.com/the-struggle-of-dynamically-typed-languages-ef91a87164a1
  5. https://www.notion.so/mkrs2404/Golang-Generics-6f6fbec208eb458fbc753aa4fd690b6d