课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing

Go data structures

- [Instructor] Many programming languages such as Java and C# have implementations of the common data structures we have seen. Go has only a handful. Remember, we established that slices are flexible abstractions on top of arrays. They can be initialized using square brackets followed by the initial elements in curly braces. Elements can be accessed by index or using a loop with a range operator. The append function adds a new element to the end of the slice and handles all array growing and element copying under the hood. The len function returns the number of elements stored in the slice while the cap function returns the capacity of the underlying array. One thing that's important to remember when working with slices is that they contain references to data, not data itself. Let's have a look at an example. We begin by creating an int array containing the integers 10 to six. Then we create two slices, one with the first two elements, and one with the last three elements. Then we append the element zero to the starting slice, expanding it with an extra element. The example contains printouts of data before and after the modification. Running this code will demonstrate the behavior of slices. We start with the data in its expected state with the start slice containing the elements 10 and nine, while the end slice contains elements from eight to six. After the modifications, the start slice is extended, containing one more element with a zero added on the end. Since the underlying array already contained an element at index two, the appended zero value has overwritten the value of eight, and this has affected the end slice as well as the original array. The example demonstrates that slices share underlying data arrays. Making changes to any slice or the array itself affects all other slices that contain references to this shared data. Maps are another interesting built-in Go data structure that's used almost as often as slices. Maps are Go's implementation of hash tables, and they are key value stores. They're initialized using the make function, which allocates all the structures it requires. Values are saved and retrieved using their corresponding key. In this example, we initialize a map with string keys and int values. The key we add data with is Anna. Elements are also deleted with the delete function, and maps return an optional return value during element lookup, which indicates the existence of a key value pair. One final thing to note is that maps are referenced types, so modifications to them will persist outside of function scope. Go's inbuilt data types, its structs, and interfaces can be used to implement any of the data structures that we have seen in the previous section. Having a good understanding of the Go standard types will enable us to do just that.

内容