This is a creation in Article, where the information may have evolved or changed.
These two days to write code when encountered such a problem, is to slice add elements of such a simple small problem, but because of negligence, blocked for a long time, now share, to avoid the subsequent recidivism.
The code begins with this:
make(map[string]string, 3)// 这里随便个例子urls["baidu""www.baidu.com"urls["google""www.google.com"urls["csdn""www.csdn.net"make([]stringlen(urls))forrange urls { append(names, key)}
At first glance, that seems to be the case, but in fact? Let's go ahead and print the names.
fmt.Println(names)
This output is obtained:
At that time wrote hurriedly, looked at the output, just puzzled a bit, how many to take a few spaces? But did not care too much, is so few look at the space to give me the pit miserable, the data obtained in the back is not right, in print the length of names:
Here the problem should be very obvious, low-level mistakes Ah!
I naively thought I had created an empty slice, and then I could fill it with append,
But the reality is that append anyway is to the tail of slice append data, he does not care you slice empty, the original slice only 3 length, now every time append to be reassigned once memory, a few operations after long ago is changed, so only honest from [0 ] Start filling in the data!