Up to Main Index                           Up to Journal for October, 2012

                    JOURNAL FOR MONDAY 29TH OCTOBER, 2012
______________________________________________________________________________

SUBJECT: Insidiously sliced bugs
   DATE: Mon Oct 29 21:33:14 GMT 2012

When coding in Go one thing that keeps tripping me up is unintentional
modification of slice data when passing slices as parameters to functions and
methods. I wish I could use something like:

  f(x []string)
  f(x *[]string)

However I know this wouldn't work because slices contain references. When you
pass a slice it contains a pointer to the underlying array data, the slices
length and capacity. This makes passing slices fast. It also means that
although a slice is passed by value you can still modify the underlying array
through the slice's reference - although you cannot modify the length or
capacity unless the slice is passed as a pointer. There is a good article by
Andrew Gerrand on the Go blog here:


  https://blog.golang.org/2011/01/go-slices-usage-and-internals.html


So why do I bring this up? I've been writing a lot of test cases for WolfMUD
using table driven tests[1]. I've also spent the last 3 hours or so debugging
an instance where a New function was modifying a slice passed as a parameter.
The result was it was modifying the test data and corrupting the table for all
the rest of the tests. Not time well spent when I'm trying to get everything
ready for releasing the prototype.

All fixed now - 1 day left to go...

--
Diddymus

  [1] See this Go wiki entry:
      https://code.google.com/p/go-wiki/wiki/TableDrivenTests



  Up to Main Index                           Up to Journal for October, 2012