Created
March 10, 2022 09:20
-
-
Save pwmcintyre/0e02040c80b7f59b6bcc3bfe5cac24c8 to your computer and use it in GitHub Desktop.
Do not rely on map order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package equal_test | |
import ( | |
"testing" | |
) | |
func TestMapOrder(t *testing.T) { | |
for i := 0; i < 100; i++ { | |
a := map[string]interface{}{ | |
"a": "foo", | |
"b": int64(1), | |
"c": float64(1), | |
} | |
b := map[string]interface{}{ | |
"a": "foo", | |
"b": int64(1), | |
"c": float64(1), | |
} | |
// Go specifically randomizes the order of a map | |
// https://go.dev/blog/maps | |
if Pluck(0, a) != Pluck(0, b) { | |
t.Fatalf("not equal at %d", i) | |
} | |
} | |
} | |
// Pluck returns the nth element of a map | |
func Pluck(nth int, thing map[string]interface{}) interface{} { | |
i := 0 | |
for _, val := range thing { | |
if nth == i { | |
return val | |
} | |
i++ | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment