Ir al contenido principal

Entradas

Mostrando entradas de abril, 2024

Go: Calculating the MD5 hash of a struct

In some scenarios, calculating the hash of a piece of data is useful, for instance when you only need to know that something in the dataset has changed, no matter what. Calculating a hash is moderately computing consuming but has some advantadges: Avoids checking the changes field by field of the dataset Allows storing only the data hash instead of the whole dataset In Golang, calculating MD5 hashes of structs can be achieved by using a code piece as this: import ( "bytes" "crypto/md5" "encoding/gob" "encoding/hex" "fmt" ) // Random struct, just for demo purposes type MySubStruct struct { Zaz *bool } type MyStruct struct { Foo int Bar []string Baz MySubStruct } func main() { // Hasheable struct myBool := false myStruct := MyStruct{ Foo: 67372388, Bar: []string{"b", "ar", ""}, Baz: MySubStruct{ Zaz: &myBool, }, } // Crea