A small detail of golang:make,slice and append

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.