Bug: Unmarshal in loop (Golang).

I’ve just stumbled into the bug trying 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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.