Bug: Unmarshal in loop (Golang)

2017/05/14

I’ve just stumbled into the bug trying to unmarshal the entries from boltdb. Here is my code:

// Get all entities from boltdb
var data [][]byte
 if data, err = db.GetAll(bucketTwitterDatasources); err != nil {
  return nil, err
 }
// Unmarshal values and keep them in the slice
var ds TwitterDataSource <<<<<< Wrong!
 for _, d := range data {
  
  if err = json.Unmarshal(d, &ds); err != nil {
   log.Printf("[ERROR] %s", err.Error())
   continue
  }
  
  dataSources = append(dataSources, ds)
 }

During the test, I noticed that I receive partially incorrect data: some fields of struct were duplicated.

The problem is the wrong place for declaration of variable “ds”.

var ds TwitterDataSource

The variable was initiated outside the loop. That means ds was initiated only once.

Before I mistakenly supposed that Unmarshal is replacing the old value completely, but it doesn’t! So I moved declaration of var ds inside the loop and all works as intended.

>> Home