Set of indefinite lengths in Go

Source: Internet
Author: User
If you're using a programming language like C # or Java to go, the first thing you'll find is that there's no traditional collection type like ' List ' and ' Dictionary '. It's been confusing me for months. I found a package called ' container/list ' and almost used it to do everything. I always have a voice in my head nagging. Language designers should not directly support the functionality of collection management for unknown lengths. Everyone is talking about how slices are widely used in languages, but I only use slices when there is a clearly defined capacity or when they are returned through a function, which is something wrong!! So I wrote an article earlier this month that uncovered the lid of the slice, hoping to find some magic that I didn't know about. I now know how slices work, but in the end I still need an array of constant length growth. I learned in school that using a linked list is more efficient and a better way to store large amounts of data. Especially when the set length you need is unknown. It means a lot to me. When I think about using an empty slice, I have a very bad image in my head:! [Slice-copy] (https://raw.githubusercontent.com/studygolang/gctt-images/master/Collections-Of-Unknown-Length-in-Go/ Slice-copy.png) I've been thinking about how go is creating a lot of new slice values and underlying arrays to do a lot of memory allocations, and replicate the values constantly. The garbage collector then works excessively because all of these small variables are created and destroyed. I can't imagine having to do this thousands of times. There's actually a better way or more efficient way I didn't realize. After studying and presenting a lot of questions, I came to the conclusion that in most practical cases, using slices is better than using a linked list. That's why language designers take the time to make slices work as efficiently as possible, and there's no reason to introduce collection types. We can discuss various boundary conditions and performance issues for several days in a row, but go wants us to use slices. So slicing should be our first choice unless the code tells us there is a problem. Mastering slices is like learning chess games, easy to learn but takes a lifetime to become a master. Because the underlying array can be shared, there are some issues to be aware of in use. Before you continue reading, you'd better look at my other article [Understanding Slices in Go programming] (http://www.goinggo.net/2013/08/ understanding-slices-in-go-programming.html). The remainder of this article explains how to use theThe slice handles the problem of unknown capacity and the operation mechanism of the slice. The following is an example of using an empty slice to manage an unknown length collection: ' ' Gopackage mainimport ("FMT" "Math/rand" "Time") type Record struct {ID int Name string Color stri Ng}func Main () {//Let ' s keep things unknown random: = Rand. New (Rand. Newsource (time. Now (). Unix ())//Create a large slice pretending we retrieved data//from a database data: = Make ([]record, +)//create th E data set for record: = 0; Record < 1000; record++ {pick: = random. INTN Color: = "Red" if pick = = 2 {color = "Blue"} Data[record] = record{Id:record, name:fmt. Sprintf ("Rec:%d", record), Color:color,}}//Split the records by Color var red []record var blue []record for _, Reco RD: = Range Data {if record. Color = = "Red" {red = append (red, record)} else {blue = append (blue, Record)}}//Display the Counts FMT. Printf ("red[%d] blue[%d]\n", Len (Red), Len (blue)} "" When we run this program, we will get red and blue slices of different lengths due to the random number generator. We cannot know in advance the capacity needs of red or blue slices, which is a typical case for me. Let's break out the more important part of the code: these two lines of code create an empty slice. "' Govar red []recordvar Blue []record '] an empty slice length and capacity is 0, andAnd there is no underlying array. We can use the built-in ' append ' function to add data to the slice. "' Gored = append (red, record) Blue = append (blue, record) ' Append ' function is very cool and does a lot of things for us. Kevin Gillette in My panel discussion: (HTTPS://GROUPS.GOOGLE.COM/FORUM/#!TOPIC/GOLANG-NUTS/NXYUMX55B6C) stated in the Go Speech specification that The first thousands of elements double the capacity each time the capacity grows, and then increase the capacity at the rate of ~1.25. I am not a scholar, but I see quite a lot using the tilde (~). Some people may not know what this means, it means about. Therefore, the ' append ' function increases the capacity of the underlying array and reserves space for future growth. The final ' append ' function will increase in capacity by approximately 1.25 or 25% of the coefficients. Let's prove that the ' append ' function grows capacity and runs efficiently: ' Gopackage mainimport ("FMT" "reflect" "unsafe") Func main () {var data []string for record: = 0; Record < 1050; record++ {data = append (data, FMT. Sprintf ("Rec:%d", record)) if record < 10 | | Record = = 256 | | Record = = 512 | | Record = = 1024x768 {sliceheader: = (*reflect. (Sliceheader) (unsafe. Pointer (&data)) fmt. Printf ("index[%d] len[%d] cap[%d]\n", record, Sliceheader.len, Sliceheader.cap)}} "output: ' ' index[0] len[1] cap[1] INDEX[1] len[2] cap[2]index[2] len[3] cap[4]-Ran out of room, Double capacityindex[3] len[4] cap[4]index[4] len[5] Cap[8 ]-Ran out of room, Double capacityindex[5] len[6] cap[8]index[6] len[7] cap[8]index[7] len[8] cap[8]index[8] len[9] cap[16]-Ran out of Roo M, double capacityindex[9] len[10] cap[16]index[256] len[257] cap[512]-Ran out of room, Double capacityindex[512] len[51 3] cap[1024]-ran out of room, Double capacityindex[1024] len[1025] cap[1280]-ran out of room, Grow by a factor of 1.25 "If we look at the capacity values, we can see that Kevin is absolutely right." Capacity is growing as he says. In the first 1000 of the elements, the capacity increased by one times. Then the volume grows with a factor of 1.25 or 25%. This means that using slices in this way will satisfy the performance we need in most cases, and memory will not be a problem. I initially thought that a new slice value would be created for each call to ' append ', but that is not the case. When we call ' append ', a copy of ' Red ' is duplicated in the stack. Then when ' Append ' returns, a copy operation is made, but the memory we have is used. "' Gored = append (red, record) ' In this case, the garbage collector is not working, so we have no performance or memory issues at all. My thoughts of C # and reference types hit me again. Please sit down, because the tiles in the next version will change. Dominik Honnef has created a blog that explains what is being written in Go tip in a concise English (thank you). These are the contents of the next release. This is a link to his blog and the section about slices in his blog. This is a great blog, recommended to read. http://dominik.honnef.co/go-tip/http://dominik.honnef.co/go-tip/2013-08-23/#slicing你可以用切片做很多的事情, You can even write a whole book about the subject. As I said before, slicing is like chess, easy to learn but it takes a lifetime to become a master. If you are from another language, such as C # and Java, then embrace the slice and use it. This is Go in the right way.

Via:https://www.ardanlabs.com/blog/2013/08/collections-of-unknown-length-in-go.html

Author: William Kennedy Translator: Althen proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

186 Reads

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.