Nugget Post: Golang : Gobs and exported identifiers

This one had me scratching my head for a while… while messing around with “gobs” – binary representation of data that can be sent over the network between two golang programs – I ran into the problem of “exported fields”. I had followed the post on the golang blog regarding gobs, with some modifications. I had initially defined the struct to be transferred as a gob like so:

type Person struct {
	name     string
	surname  string
	age      int64
	employed bool

However this didn’t go down well and the receiving end started seeing:

{ 0, false}

Which basically means an empty struct of type Person (sidenote: when golang is not passed values for fields in a struct, it inserts “defaults”, these being empty for strings, 0 for integers, and false for boolean – hence explaining the output I was receiving}. The problem was not obvious to me (though it was in hindsight, as you can see in my comments in the code of my golang learning repo). The problem was to do with “exported identifiers“. In golang, one way of making sure that identifiers (or fields of a struct) remain private (in java parlance) is to give them a variable name beginning with a small letter. Public or exported (visible to all packages and functions) identifiers must start with a capital letter. So changing the above Person struct to:

type Person struct {
	Name     string
	Surname  string
	Age      int64
	Employed bool

resolved my issue in a hurry. Once I knew what to look for, in all fairness, if I had RTFM properly i’d have seen the following in the gobs blogpost:

// Only exported fields are encoded and decoded