Why use reflection here?

Hi, I’m fairly new to golang and I did stumble upon this code in k8s/k8s:

var providers = make(map[string]DockerConfigProvider)
[…]

keys := reflect.ValueOf(providers).MapKeys()
stringKeys := make([]string, len(keys))
for ix := range keys {
	stringKeys[ix] = keys[ix].String()
}
sort.Strings(stringKeys)

Why is reflection used here? The map key type is know and string, so why did the author use reflection here?

Any ideas?
Idiomatic golang would be to iterate over the map.
Looking at the commit it was done for Make CredentialProvider config loading deterministic. · kubernetes/kubernetes@804ee25 · GitHub
For sorting after map key reasons, but I don’t understand why to use reflection here still.

From this code snippet, it looks like it’s not using a lock to get a snapshot list of the map because of data races, it just saves some troublesome work. You can try viewing the source code of MapKeys.

1 Like

Git blame sheds some light on the question here. In short, they wanted this algorithm to be more deterministic than simply iterating over map keys, since the order of keys access is random.

But why not build an array of all keys and sort it without using reflection?
The missing mutex for access the data structure looks wrong also, not sure how MapKeys would alleviate this problem.

maybe you can send an email for the answer

FYI

Reading the map source code of golang show that there are actually two different map implementation: the experimental SwissMap and this great blog post I found