Decode does not zero the destination variable before decoding the value into it.

Author: curioustolearnCreated Feb 14, 2017Updated Jul 4, 2024

I realized today that Decode does not zero the destination variable before decoding the value into it. Is this expected; or is this a bug?

Example:


	var rec r.ChangeResponse
	var updatedDec UserDecision

      	go func() {
		for cur.Next(&rec) {
			newValInterface := rec.NewValue
			fmt.Printf("\nNewvalue: %+v\n", newValInterface)
			fmt.Printf("\nupdatedDec: %+v\n", updatedDec) 
			mapstructure.Decode(newValInterface, &updatedDec) 
			fmt.Printf("\nDecision update: %+v\n", updatedDec)
			decUpdateCh <- updatedDec
		}
		log.Println("Exiting goroutine listening on decUpdate changes.")
	}()

In the above example updatedDec is not zeroed across iterations. updatedDec contains an array. If that array has more elements than the same array in the new value, then some of the earlier values remain in there after mapstrucure.Decode.