TRANSCODE Explorations into the Code Transcendental.

Going Generic

Going Generic

My Grandmother will often buy generic brands at the grocery to save a few dollars. A child of the depression, she knows the true value of a thing1. Go could take a lesson from her.

Let me provide an example. Here is code to concat two array of string.2

func concat(a, b []string) []string {
  ret := make([]string, len(a) + len(b))
  copy(ret, a)
  copy(ret[len(a):], b)
  return ret
}

It can only be used for []string values. Nothing else. If I need to concat two int arrays, well then I need another function.

func concat(a, b []int) []int {
  ret := make([]int, len(a) + len(b))
  copy(ret, a)
  copy(ret[len(a):], b)
  return ret
}

There is no difference between these two functions except the array’s element type. Ideally a general solution would allow use to name the type, e.g.

func concat(a, b []<t>) []<t> {
  ret := make([]<t>, len(a) + len(b))
  copy(ret, a)
  copy(ret[len(a):], b)
  return ret
}

From what I have heard there are some strict criteria to be met for any general solution to this issue. I plan to do some further reading.

  1. Sometimes too much so actually. Of an emptied product container she’ll often say, “this is fine container, surely you must have something you can put in it”. :) 

  2. Yes, there is simpler way to concat two arrays, i.e. append(a1, a2...), but the concat function makes for a clear example of the generics issue. The specific functionality is not important.